diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000..dd84ea78 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,38 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Desktop (please complete the following information):** + - OS: [e.g. iOS] + - Browser [e.g. chrome, safari] + - Version [e.g. 22] + +**Smartphone (please complete the following information):** + - Device: [e.g. iPhone6] + - OS: [e.g. iOS8.1] + - Browser [e.g. stock browser, safari] + - Version [e.g. 22] + +**Additional context** +Add any other context about the problem here. diff --git a/.github/workflows/create_release.yml b/.github/workflows/create_release.yml new file mode 100644 index 00000000..38fa5ed1 --- /dev/null +++ b/.github/workflows/create_release.yml @@ -0,0 +1,45 @@ +# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven + +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. + +name: Create release + +on: + workflow_dispatch: + +env: + MINECRAFT_VERSION: 1.20.4 + +jobs: + build: + permissions: + contents: write + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up Java 17 + uses: actions/setup-java@v3 + with: + java-version: '17' + distribution: 'temurin' + cache: maven + - uses: SpraxDev/Action-SpigotMC@v4 + with: + versions: ${{ env.MINECRAFT_VERSION }}, + remapped: true + - name: Build with Maven + run: mvn '-Dproject.artifactOutput=.' -B package --file pom.xml + - name: Create Release + uses: ncipollo/release-action@v1.14.0 + with: + artifacts: jrides.jar + name: jrides ${{ env.MINECRAFT_VERSION }}-${{ github.run_number }} + makeLatest: true + commit: master + tag: release-${{ github.run_number }} diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml new file mode 100644 index 00000000..531f25ea --- /dev/null +++ b/.github/workflows/maven.yml @@ -0,0 +1,43 @@ +# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven + +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. + +name: Maven build + +on: + push: + branches: [ "master" ] + pull_request: + branches: [ "master" ] + +env: + MINECRAFT_VERSION: 1.20.4 + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up Java 17 + uses: actions/setup-java@v3 + with: + java-version: '17' + distribution: 'temurin' + cache: maven + - uses: SpraxDev/Action-SpigotMC@v4 + with: + versions: ${{ env.MINECRAFT_VERSION }}, + remapped: true + - name: Build with Maven + run: mvn '-Dproject.artifactOutput=.' '-DartifactFileNameSuffix=_devbuild_${{ github.run_number }}' -B package --file pom.xml + - name: Upload Artifact + uses: actions/upload-artifact@v4 + with: + name: jrides ${{ env.MINECRAFT_VERSION }} nr.${{ github.run_number }} Development Build + path: jrides_devbuild_${{ github.run_number }}.jar diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..97f75fb6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,177 @@ +# Created by https://www.toptal.com/developers/gitignore/api/java +# Edit at https://www.toptal.com/developers/gitignore?templates=java + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +# End of https://www.toptal.com/developers/gitignore/api/java + +# Created by https://www.toptal.com/developers/gitignore/api/maven +# Edit at https://www.toptal.com/developers/gitignore?templates=maven + +### Maven ### +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +# https://github.com/takari/maven-wrapper#usage-without-binary-jar +.mvn/wrapper/maven-wrapper.jar + +# Eclipse m2e generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +# End of https://www.toptal.com/developers/gitignore/api/maven + +# Created by https://www.toptal.com/developers/gitignore/api/intellij +# Edit at https://www.toptal.com/developers/gitignore?templates=intellij + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +.idea/artifacts +.idea/compiler.xml +.idea/jarRepositories.xml +.idea/modules.xml +.idea/*.iml +.idea/modules +*.iml +*.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ +.idea +jrides.iml + +# VS Code +.vscode/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +# End of https://www.toptal.com/developers/gitignore/api/intellij \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..e72bfdda --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 00000000..38c8ed32 --- /dev/null +++ b/README.md @@ -0,0 +1,77 @@ +![](assets/banner-1.gif) + +# **jrides** - Bring coasters to your Minecraft server! +![Maven build](https://github.com/JVerbruggen/jrides/workflows/Maven%20build/badge.svg) + + +'jrides' is an open-source rollercoaster animator for Minecraft Spigot. Super-smoothly animated coasters within the snap of a finger. + +✨ **No mods required!** ✨ + +## 🎢 *Ride - go inside your own rides* +* With jrides, you can enter any ride you create. Whether it is a launched, inverted or water coaster. + +![](assets/banner-2.gif) + + + +## 🎛️ *Control - send your friends onto the lift-hill* +* Be the person behind the buttons! You decide whether the ride is safe for dispatch or not. +* Not interested in being behind the controls, or no player online to control the ride? No problem! Put the ride in automatic mode! + +**And with the advanced ride monitoring system, you know where all trains are, without even seeing them!** + +![](assets/banner-3.gif) + + +## 🚠 *Go sideways - hyper-mobile transfers* +* Besides going forward, your coaster can go sideways, if you want! Use transfers to push a train sideways, upwards, or even roll it on its side. + +![](assets/banner-4.gif) + +## 😵‍💫 *SmoothCoasters - upside down POV camera* +With built-in support for the [smooth-coasters client](https://www.curseforge.com/minecraft/mc-mods/smoothcoasters), you can go upside down! + +## ✨ And so much more! +* Custom **Flat rides** - i.e. TeaCups, Caroussels, Ferris Wheels, anything that rotates! +* Flat ride passenger control +* Navigation menu +* Ride counters +* Double stations +* Multi-track support, redirect your trains left or right +* Player teleportation system + + +--- + +## Download + +Click one of the versions below to start your download! Thank you and enjoy! + +| Version | Link | +|---------|-----| +| 1.19.2 | tbd | +| 1.20.1 | tbd | + +### Warning - jrides is currently in beta. Please report any issues in GitHub. + +
+ +## Configuration +Refer to [docs/config.md](./docs/config.md) for configuration. + + +--- + +## 🎡 **Visit our live demo!** server.greekcraft.nl +Try it out for yourself! Join our demo server at [server.greekcraft.nl](https://greekcraft.nl). + +
+ +**Trailer video** + +[![GreekCraft trailer](https://img.youtube.com/vi/pJAwFTujA9M/0.jpg)](https://www.youtube.com/watch?v=pJAwFTujA9M) + +--- + +*jrides - created by [MeneerPinguin](https://github.com/JVerbruggen)* diff --git a/assets/banner-1.gif b/assets/banner-1.gif new file mode 100644 index 00000000..bcf521cf Binary files /dev/null and b/assets/banner-1.gif differ diff --git a/assets/banner-2.gif b/assets/banner-2.gif new file mode 100644 index 00000000..cc3e8b39 Binary files /dev/null and b/assets/banner-2.gif differ diff --git a/assets/banner-3.gif b/assets/banner-3.gif new file mode 100644 index 00000000..6764ad9c Binary files /dev/null and b/assets/banner-3.gif differ diff --git a/assets/banner-4.gif b/assets/banner-4.gif new file mode 100644 index 00000000..9812d074 Binary files /dev/null and b/assets/banner-4.gif differ diff --git a/docs/assets/coaster-creation-flow.drawio.png b/docs/assets/coaster-creation-flow.drawio.png new file mode 100644 index 00000000..80e315e7 Binary files /dev/null and b/docs/assets/coaster-creation-flow.drawio.png differ diff --git a/docs/assets/source/coaster-creation-flow.drawio b/docs/assets/source/coaster-creation-flow.drawio new file mode 100644 index 00000000..124cd4fa --- /dev/null +++ b/docs/assets/source/coaster-creation-flow.drawio @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/coaster_yml.md b/docs/coaster_yml.md new file mode 100644 index 00000000..e9c13940 --- /dev/null +++ b/docs/coaster_yml.md @@ -0,0 +1 @@ +# Coaster.yml diff --git a/docs/config.md b/docs/config.md new file mode 100644 index 00000000..f287c16e --- /dev/null +++ b/docs/config.md @@ -0,0 +1,47 @@ +# Configuration + +## Folder structure + +Default data folder +* `plugins/jrides` + +## rides.yml +* This file contains all active coasters that should be loaded on startup. +* Location: `plugins/jrides/rides.yml` + +Example configuration: +```yml +config: + silverstar: + identifier: silverstar + type: coaster + wodan: + identifier: wodan + type: coaster +``` + +## language.yml +* Change all feedback that is visible to players. +* Location: `plugins/jrides/language.yml` + +Example configuration: +```yml +language: + NOTIFICATION_RIDE_COUNTER_UPDATE: "&4-------\n \n&6You have been %RIDE_COUNT% times in %RIDE_DISPLAY_NAME%!\n \n&4-------" + NOTIFICATION_CANNOT_ENTER_RIDE: "&7This ride is temporarily unavailable." +``` + +For all available language overrides, see [docs/language.md](./language.md) + + +## coaster.yml +* Coaster configuration +* Location: `plugins/jrides/coasters//.coaster.yml` +* * Example: `plugins/jrides/coasters/silverstar/silverstar.coaster.yml` + +The exact structure of this file can be found in [docs/coaster_yml.md](./coaster_yml.md) + +## trigger.yml +* Add triggers to coaster tracks, to run effects, commands or animate entities. + +For more information, see [docs/triggers.md](./triggers.md) \ No newline at end of file diff --git a/docs/item.md b/docs/item.md new file mode 100644 index 00000000..8f7aaa16 --- /dev/null +++ b/docs/item.md @@ -0,0 +1,2 @@ +# Item configuration + diff --git a/docs/language.md b/docs/language.md new file mode 100644 index 00000000..79efc9b3 --- /dev/null +++ b/docs/language.md @@ -0,0 +1,69 @@ + +# Language + +Also see: [docs/config.md](./config.md) + +Example language file (plugins/jrides/language.yml): +```yaml +language: + NOTIFICATION_RIDE_COUNTER_UPDATE: "&4-------\n \n&6You have been %RIDE_COUNT% times in %RIDE_DISPLAY_NAME%!\n \n&4-------" + NOTIFICATION_CANNOT_ENTER_RIDE: "&7This ride is temporarily unavailable." +``` + +Key | Default value +--- | --- +CHAT_FEEDBACK_PREFIX | "[jrides] " +CHAT_FEEDBACK_INFO_COLOR | "&7" +CHAT_FEEDBACK_WARNING_COLOR | "&e" +CHAT_FEEDBACK_SEVERE_COLOR | "&c" +COMMAND_RIDE_DISPATCHED_MESSAGE | "Ride %RIDE_DISPLAY_NAME% was dispatched!" +COMMAND_VISUALIZE_ADDED_VIEWER | "You are now viewing %RIDE_IDENTIFIER% in visualize mode" +COMMAND_VISUALIZE_REMOVED_VIEWER | "You are no longer viewing %RIDE_IDENTIFIER% in visualize mode" +NOTIFICATION_PLUGIN_STILL_LOADING | "Please try again later when jrides is loaded" +NOTIFICATION_RIDE_CONTROL_ACTIVE | "You are now controlling %RIDE_DISPLAY_NAME%" +NOTIFICATION_RIDE_CONTROL_INACTIVE | "You are no longer controlling %RIDE_DISPLAY_NAME%" +NOTIFICATION_RIDE_DISPATCH_PROBLEMS | "Cannot dispatch due to the following problems:" +NOTIFICATION_RIDE_NO_TRAIN_PRESENT | "No train present in station" +NOTIFICATION_RIDE_NEXT_BLOCK_OCCUPIED | "Next block section is occupied" +NOTIFICATION_RIDE_WAITING_TIME | "Waiting time has not passed yet" +NOTIFICATION_RIDE_RESTRAINTS_NOT_CLOSED | "Not all restraints are closed" +NOTIFICATION_RIDE_GATES_NOT_CLOSED | "Not all gates are closed" +NOTIFICATION_RIDE_GATE_NOT_CLOSED | "Gate %NAME% is not closed" +NOTIFICATION_RIDE_COUNTER_UPDATE | "\nYou've ridden %RIDE_DISPLAY_NAME% %RIDE_COUNT% times now\n" +NOTIFICATION_RIDE_STATE_OPEN | "%RIDE_DISPLAY_NAME% is now open" +NOTIFICATION_RIDE_STATE_CLOSED | "%RIDE_DISPLAY_NAME% is now closed" +NOTIFICATION_SHIFT_EXIT_CONFIRMATION | "Press shift again within 2 seconds to confirm exiting the ride" +NOTIFICATION_SHIFT_EXIT_CONFIRMED | "You just exited the ride while the restraints were closed" +NOTIFICATION_DISPATCH_WAIT_GENERIC | "Please wait until the ride is dispatched" +NOTIFICATION_DISPATCH_WAIT_SPECIFIC | "Waiting time: %TIME% seconds" +NOTIFICATION_RESTRAINT_ON_EXIT_ATTEMPT | "The restraints are closed" +NOTIFICATION_RESTRAINT_ON_ENTER_ATTEMPT | "The restraints are closed" +NOTIFICATION_RESTRAINT_ENTER_OVERRIDE | "You just entered the ride while the restraints were closed" +NOTIFICATION_CANNOT_ENTER_RIDE | "You currently cannot enter this ride, try again later" +NOTIFICATION_CANNOT_ENTER_RIDE_CLOSED | "This ride is currently closed" +NOTIFICATION_OPERATOR_IDLE_TOO_LONG | "You were idle for too long while operating %RIDE_DISPLAY_NAME%" +NOTIFICATION_WARPED | "" +ELEVATED_OPERATOR_OVERRIDE_VICTIM_MESSAGE | "Player %PLAYER% took over control of the operating cabin" +ERROR_SMOOTH_COASTERS_DISABLED | "Smoother ride experience is disabled, please install SmoothCoasters" +ERROR_GENERAL_NO_PERMISSION_MESSAGE | "You do not have permissions to execute this action" +ERROR_PLAYER_COMMAND_ONLY_MESSAGE | "Only players can execute this command" +ERROR_UNKNOWN_COMMAND_MESSAGE | "Unknown jrides command. Type '/jrides help' for help" +ERROR_OPERATING_CABIN_OCCUPIED | "You can not take this operating cabin since it is already in use by another operator" +ERROR_OPERATING_NO_PERMISSION | "You are not allowed to operate this ride" +ERROR_RIDE_CONTROL_MENU_NOT_FOUND | "Ride control menu was not found" +ERROR_RIDE_OVERVIEW_MAP_NOT_FOUND | "Could not retrieve map for ride %RIDE_IDENTIFIER%, was the map id configured?" +MENU_RIDE_OVERVIEW_TITLE | "Ride overview menu" +MENU_RIDE_OVERVIEW_STATUS_OPEN | "This ride is currently opened" +MENU_RIDE_OVERVIEW_STATUS_CLOSED | "This ride is currently closed" +MENU_RIDE_OVERVIEW_STATUS_MAINTENANCE | "This ride is in maintenance" +MENU_RIDE_CONTROL_TITLE | "Ride control menu" +MENU_ADMIN_RIDE_CONTROL_TITLE | "Admin ride control menu" +BUTTON_CLAIM_CABIN | "Claim operating cabin" +BUTTON_CABIN_CLAIMED | "Claim operating cabin" +BUTTON_DISPATCH_STATE | "Dispatch" +BUTTON_DISPATCH_PROBLEM_STATE | "Not allowed" +BUTTON_PROBLEMS_STATE | "Problems" +BUTTON_GATES_OPEN_STATE | "Gates are open" +BUTTON_GATES_CLOSED_STATE | "Gates are closed" +BUTTON_RESTRAINTS_OPEN_STATE | "Restraints are open" +BUTTON_RESTRAINTS_CLOSED_STATE | "Restraints are closed" diff --git a/docs/permissions.md b/docs/permissions.md new file mode 100644 index 00000000..7df2977c --- /dev/null +++ b/docs/permissions.md @@ -0,0 +1,39 @@ +# Permissions + +## Default + +Permission | Description +--- | --- +jrides.default.ride_enter | Allow entering a ride +jrides.default.warp | Allow warping (through menu) +jrides.command.default.warp | Allow warping (through command) + +## Operator + +Permission | Description +--- | --- +jrides.operator.cabin_operate | Allow to operate in a ride cabin +jrides.command.operator | Allow '/jrides control' command +jrides.command.operator.dispatch | Allow '/jrides control dispatch' command +jrides.command.operator.menu | Allow '/jrides control menu' command + +## Elevated (admin) + +Permission | Description +--- | --- +jrides.elevated.restraint_override | Allow to override restraint lock +jrides.elevated.operator_override | Allow to take over an operator in a cabin +jrides.elevated.closed_ride_enter_override | Allow to override closed ride entering +jrides.elevated.open_state_change | Allow to open or close a ride +jrides.command.elevated | Base for elevated commands (for admins) +jrides.command.elevated.admin_menu | Allow to open ride admin menu +jrides.command.elevated.ride_overview | Allow for generating a ride overview map +jrides.command.elevated.block_section | Allow for getting block section occupation message (debug) +jrides.command.elevated.visualize | Allow to visualize a coaster spline (debug) + +## Debug + +Permission | Description +--- | --- +jrides.elevated.status_inspection | Allow to inspect coaster frames (debug) + diff --git a/docs/plugin_update.md b/docs/plugin_update.md new file mode 100644 index 00000000..70271d23 --- /dev/null +++ b/docs/plugin_update.md @@ -0,0 +1,43 @@ +# Plugin update + +To manually build jrides on a new spigot version, follow this guide. + +## 1. Run build tools + +Go to: +https://www.spigotmc.org/wiki/buildtools/ + +and download the latest BuildTools. + +Run BuildTools with the '--remapped' option, or in the gui with 'Remapped Jars'. + +## 2. Add new build profile to pom.xml +```xml + + jrides-1.20.1 + + true + + + 1.20.1 + 1.20 + 1.20 + + +``` + +Make sure to select the new profile in your Maven configuration. + +## 3. Check dependency versioning +ProtocolLib usually has a new version for the new minecraft version. Update all dependencies in maven and on your test server. + +## 4. Create a new PacketSender instance +In the jrides repository, go to `com.jverbruggen.jrides.packets.impl` and create a new implementation for your new Minecraft version. + +Also make sure to register this implementation in the PacketSenderFactory. + +## 5. Update the maven workflow +In jrides repository, go to .github/workflows and edit the maven.yml. Update the Action-SpigotMC version to the new latest version. + +## 6. Build with Maven +Finally, run a jrides build with Maven. \ No newline at end of file diff --git a/docs/triggers.md b/docs/triggers.md new file mode 100644 index 00000000..2d9813ae --- /dev/null +++ b/docs/triggers.md @@ -0,0 +1,219 @@ +# Triggers + +Triggers are tools that are used for creating all sorts of effects alongside the rides themselves. +'jrides' has various types of triggers, each of them listed below. + +## Adding triggers to a track + +### Summary + +Triggers can only exist when defined. Definitions can be found in multiple places. + +1. In the `.default.trigger.yml` file, used for placing triggers alongside the default track. +2. In the `.coaster.yml` file ([link](./coaster_yml.md)), used for section types that support triggers, such as the `type: station` section type. +3. In another track's trigger file, other than the default track. Just like the `.default.trigger.yml` file, each registered track can have its own trigger file. The trigger file name should be called `..trigger.yml`. + +### File structure + +As said, the file name of the general trigger.yml file is as follows: `..trigger.yml`. The contents of this file is defined here. + +```yml +triggers: + : + frame: + : + frame: + ... +``` + +for example: + +```yml +triggers: + start-chain-hook-sound: + frame: 500 + stop-chain-hook-sound: + frame: 2300 + people-scream-sound: + frame: 3100 +``` + +Add as many triggers as you'd like. + +## Defining trigger behaviour + +### Summary + +Every trigger identifier has it's own configuration file as of what it does. These files can be found in the `coasters//triggers` folder. + +Each trigger that is defined in the general trigger.yml, needs a corresponding file in the triggers folder. The name of this file is equal to `.yml` + +For example, when using a trigger named `start-chain-hook-sound` that triggers at frame 500, a file with name `start-chain-hook-sound.yml` needs to be created in the triggers folder. + +### File structure + +Since jrides has multiple types of triggers, the structure of this file changes depending on which trigger is used. For every trigger, the following base structure is the same: + +```yml +trigger: + type: +``` + +The `trigger_type` can be either one of the following values: + +* [type: multi-entity-movement](#type-multi-entity-movement) +* [type: command](#type-command) +* [type: eject](#type-eject) +* [type: command-for-player](#type-command-for-player) +* [type: command-as-player](#type-command-as-player) +* [type: external](#type-external-for-developers) + +

+ +## Trigger specifications + +### type: multi-entity-movement + +The `multi-entity-movement` trigger can move several entities at once. Each entity has its own unique name under the `entities` attribute. + +An entity can have either an item that is displayed, or it can be a minecraft entity, such as a chicken or a horse. To see all item configuration options, check out [item.md](item.md). + +Motions can be defined in two distinct ways. +1. From position -> To position (using the `locationFrom`, `locationTo`, `rotationFrom` and `rotationTo` keys) +2. Initial position -> Continuous motion (until animation time ticks is reached) + +
+ +**From -> to animation** + +The from -> to animation type uses keys `locationFrom`, `locationTo`, `rotationFrom` and `rotationTo`, to create a linear path between two points. + +```yml +trigger: + type: multi-entity-movement + entities: + : + item: + material: APPLE + entity: # item: and entity: cannot be used simultaneously + type: HORSE + animation: + 1: + locationFrom: [50.0, 10.0, 50.0] # [x, y, z] + locationTo: [50.0, 14.0, 50.0] + rotationFrom: [0.0, 0.0, 0.0] # [pitch, yaw, roll] + rotationTo: [0.0, 90.0, 0.0] + animationTimeTicks: 60 # Duration of animation in ticks + delayTicks: 0 # Duration of delay in ticks until the animation starts + 2: + locationFrom: [50, 14, 50] + locationTo: [50, 12, 50] + animationTimeTicks: 20 +``` + +**Initial position -> Continuous motion** + +the initial -> Continuous motion type uses keys `initialLocation`, `initialRotation`, `locationDelta` and `rotationDeta` to create a continuous path after an initial location. Each tick, the delta location and rotation is added to the initials, creating a continuous motion. This can be useful for example for turning wheels. + +```yml +trigger: + type: multi-entity-movement + entities: + : + item: + material: APPLE + animation: + 1: + initialLocation: [50.0, 10.0, 50.0] # [x, y, z] + initialRotation: [0, 0, 0] # [pitch, yaw, roll] + locationDelta: [0.0, 0.1, 0.0] + rotationDelta: [0.0, 1.0, 0.0] + resetOnStart: false # whether to set the entity back to its initial position every time + animationTimeTicks: 60 # Duration of animation in ticks + delayTicks: 0 # Duration of delay in ticks until the animation starts +``` + + +--- + +### type: eject +The `eject` trigger allows to eject players early in a coaster. This is helpful (for example) when you want to eject players before the station was reached. + +```yml +trigger: + type: eject + asFinished: true # Process the ejection as if the ride was finished. Default = true +``` +--- + +### type: command + +The `command` trigger allows for flexible linkage of jrides triggers to your plugins or minecraft commands. The command defined in this trigger is ran by the console, so be careful about what is filled in here. + +**! Be aware !** Using commands is usually not a 'best-practice' in most cases, and should only be used when the [external](#type-external-for-developers) trigger type is not a viable solution. + +```yml +trigger: + type: command + command: +``` + +For example, if you want the server to run the command `/time set day`, the config would look as follows: + +```yml +trigger: + type: command + command: time set day +``` + +If you want a command to be executed that is bound to a player, you should use the `command-for-player` type. + +--- + +### type: command-for-player + +Just like the [command](#type-command) type, the `command-for-player` type is executed by the server. The main difference is that the command is executed for all passengers of the train that is passing the trigger. This means that for i.e. 6 passengers, the command is executed 6 times. + +```yml +trigger: + type: command-for-player + command: +``` + +Use the `%PLAYER%` tag in your command to replace that bit of the command with the player's name. + +```yml +trigger: + type: command-for-player + command: tell %PLAYER% Please stay seated! +``` + +If you'd like a command to be executed as if the player ran it themselves, you should use the `command-as-player` type. + +--- + +### type: command-as-player + +In contrast to the [command](#type-command) type, the `command-as-player` type is executed by the player. + +```yml +trigger: + type: command-as-player + command: +``` + +--- + +### type: external (for developers) + +The external trigger allows you to listen for a bukkit event, that is dispatched by jrides. The event that is dispatched can be found in [ExternalTriggerEvent.java](../src/main/java/com/jverbruggen/jrides/event/ride/ExternalTriggerEvent.java). + +The trigger config file has a `data` attribute, where you can store any key and value as strings. Be aware not to use anything other than strings as values to this data attribute. + +```yml +trigger: + type: external + data: + : + : +``` \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..ee3a186d --- /dev/null +++ b/pom.xml @@ -0,0 +1,313 @@ + + + 4.0.0 + + com.jverbruggen.jrides + jrides + 1.0_${minecraft.version.short} + + jrides + Bring coasters to your Minecraft server! + https://github.com/JVerbruggen/jrides + + 2023 + + + + J Verbruggen + JVerbruggen + + Lead Developer + + + + + + + GPL-3.0 + https://www.gnu.org/licenses/gpl-3.0.html + + + + + GitHub + https://github.com/JVerbruggen/jrides/issues + + + + UTF-8 + 17.0.5 + 17 + 17.0.5 + 17.0.5 + + + ${minecraft.version.short} + + ${minecraft.version.short}-R0.1-SNAPSHOT + ${minecraft.version.short.spigot}-R0.1-SNAPSHOT + + ${testServer.location}/plugins + jrides-api + /api + + ${project.artifactId}${artifactFileNameSuffix} + + ../jrides_testserver/${minecraft.version.short} + + + + + org.junit.jupiter + junit-jupiter + 5.10.2 + test + + + org.spigotmc + spigot-api + ${minecraft.version} + provided + + + org.spigotmc + spigot + ${minecraft.version.spigot} + remapped-mojang + provided + + + me.m56738 + SmoothCoastersAPI + 1.10 + compile + + + de.tr7zw + item-nbt-api-plugin + 2.12.3 + + + com.comphenix.protocol + ProtocolLib + 5.1.0 + provided + + + com.sk89q.worldguard + worldguard-bukkit + 7.0.9 + provided + + + com.google.code.gson + gson + 2.10.1 + + + + dev.cerus.maps + common + 3.8.3 + compile + + + dev.cerus.maps + plugin + 3.8.3 + compile + + + junit + junit + RELEASE + test + + + com.github.shynixn.structureblocklib + structureblocklib-bukkit-api + 2.13.0 + provided + + + + + + + src/main/resources + + plugin.yml + + true + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + true + 512m + 2048m + ${java.versioneasy} + ${java.versioneasy} + + + + net.md-5 + specialsource-maven-plugin + 1.2.4 + + + package + + remap + + remap-obf + + org.spigotmc:minecraft-server:${minecraft.version.spigot}:txt:maps-mojang + true + org.spigotmc:spigot:${minecraft.version.spigot}:jar:remapped-mojang + true + remapped-obf + + + + package + + remap + + remap-spigot + + ${project.build.directory}/${project.artifactId}-${project.version}-remapped-obf.jar + org.spigotmc:minecraft-server:${minecraft.version.spigot}:csrg:maps-spigot + org.spigotmc:spigot:${minecraft.version.spigot}:jar:remapped-obf + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.2.0 + + + jrides-api + package + + jar + + + api + + com/jverbruggen/jrides/api/**/*.class + com/jverbruggen/jrides/event/**/*.class + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.3.0 + + + + de.tr7zw.changeme.nbtapi + com.jverbruggen.jrides.nbtapi + + + com.google.code.gson + com.jverbruggen.jrides.gson + + + + + + package + + shade + + + ${artifactFileName} + ${project.artifactOutput}/${artifactFileName}.jar + ${project.artifactOutput} + + + + + + + + + + spigot-repo + https://hub.spigotmc.org/nexus/content/repositories/snapshots/ + + + sonatype + https://oss.sonatype.org/content/groups/public/ + + + + dmulloy2-repo + https://repo.dmulloy2.net/repository/public/ + + + codemc-repo + https://repo.codemc.org/repository/maven-public/ + default + + + sk89q-repo + https://maven.enginehub.org/repo/ + + + + mgdev-repo + https://ci.mg-dev.eu/plugin/repository/everything/ + + + + + + jrides-1.19.2 + + 1.19.2 + 1.19.2 + 1.19 + + + + jrides-1.20.1 + + 1.20.1 + 1.20.1 + 1.20 + + + + jrides-1.20.4 + + true + + + 1.20.4 + 1.20.4 + 1.20 + + + + + + + maven-snapshots + https://repository.apache.org/content/repositories/snapshots/ + + + + \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/JRidesPlugin.java b/src/main/java/com/jverbruggen/jrides/JRidesPlugin.java new file mode 100644 index 00000000..43cb7f0c --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/JRidesPlugin.java @@ -0,0 +1,90 @@ +package com.jverbruggen.jrides; + +import com.jverbruggen.jrides.animator.smoothanimation.SmoothAnimation; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.logging.JRidesLogger; +import com.jverbruggen.jrides.logging.LogType; +import com.jverbruggen.jrides.models.entity.BroadcastMessageReceiver; +import com.jverbruggen.jrides.models.entity.MessageReceiver; +import com.jverbruggen.jrides.packets.PacketSender; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.logging.Logger; + +public class JRidesPlugin { + private static JRidesLogger logger = null; + private static JavaPlugin plugin; + private static PacketSender packetSender; + private static SmoothAnimation smoothAnimation; + private static LanguageFile languageFile; + private static World world; + private static MessageReceiver broadcastMessageReceiver; + + public static ServiceProvider getServiceProvider(){ + return ServiceProvider.instance; + } + + public static JavaPlugin getBukkitPlugin(){ + if(plugin == null){ + throw new RuntimeException("JRidesPlugin not defined since it is not yet enabled"); + } + + return plugin; + } + + public static void setBukkitPluginHost(JavaPlugin plugin){ + JRidesPlugin.plugin = plugin; + } + + public static void initOtherStatics(){ + packetSender = ServiceProvider.getSingleton(PacketSender.class); + smoothAnimation = ServiceProvider.getSingleton(SmoothAnimation.class); + logger = ServiceProvider.getSingleton(JRidesLogger.class); + languageFile = ServiceProvider.getSingleton(LanguageFile.class); + broadcastMessageReceiver = new BroadcastMessageReceiver(); + +// logger.enableLogType(LogType.SECTIONS); + } + + public static PacketSender getPacketSender() { + return packetSender; + } + + public static SmoothAnimation getSmoothAnimation() { + return smoothAnimation; + } + + public static JRidesLogger getLogger() { + if(logger == null){ // Only occurs when not running as plugin + logger = new JRidesLogger(Logger.getGlobal(), false, false); + } + return logger; + } + + public static LanguageFile getLanguageFile() { + return languageFile; + } + + public static void setWorld(World world) { + JRidesPlugin.world = world; + } + + public static World getWorld() { + return world; + } + + private static String getBukkitVersion(){ + return Bukkit.getServer().getBukkitVersion().split("-")[0]; + } + + public static String getVersion() { + return getBukkitVersion() + "-j0.0"; + } + + public static MessageReceiver getBroadcastReceiver(){ + return broadcastMessageReceiver; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/Main.java b/src/main/java/com/jverbruggen/jrides/Main.java new file mode 100644 index 00000000..e8abf2a4 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/Main.java @@ -0,0 +1,114 @@ +package com.jverbruggen.jrides; + +import com.comphenix.protocol.ProtocolManager; +import com.jverbruggen.jrides.command.MainCommandExecutor; +import com.jverbruggen.jrides.common.MenuSessionManager; +import com.jverbruggen.jrides.common.startup.StartMessage; +import com.jverbruggen.jrides.config.ride.RideState; +import com.jverbruggen.jrides.control.uiinterface.menu.button.event.ButtonClickEventListener; +import com.jverbruggen.jrides.control.uiinterface.menu.open.SignMenuListener; +import com.jverbruggen.jrides.listener.PlayerTeleportToRideListener; +import com.jverbruggen.jrides.models.map.ridecounter.RideCounterMapListener; +import com.jverbruggen.jrides.models.entity.listener.PassengerListener; +import com.jverbruggen.jrides.models.ride.count.RideCounterRecordRideCollection; +import com.jverbruggen.jrides.state.player.BukkitPlayerJoinEventListener; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.agent.MessageAgentManagerListener; +import com.jverbruggen.jrides.models.map.rideoverview.RideOverviewMapListener; +import com.jverbruggen.jrides.models.ride.count.RideCounterListener; +import com.jverbruggen.jrides.models.ride.count.RideCounterRecord; +import com.jverbruggen.jrides.models.ride.count.RideCounterRecordCollection; +import com.jverbruggen.jrides.packets.listener.VirtualEntityPacketListener; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.serviceprovider.configuration.ServiceProviderConfigurator; +import com.jverbruggen.jrides.state.player.PlayerManager; +import com.jverbruggen.jrides.state.player.PlayerManagerListener; +import com.jverbruggen.jrides.state.ride.RideCounterManager; +import com.jverbruggen.jrides.state.ride.RideManager; +import com.jverbruggen.jrides.state.ride.SoftEjector; +import com.jverbruggen.jrides.state.ride.menu.RideMenuLoader; +import com.jverbruggen.jrides.state.viewport.ViewportListener; +import com.jverbruggen.jrides.state.viewport.ViewportManager; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.configuration.serialization.ConfigurationSerialization; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +public class Main extends JavaPlugin { + @Override + public void onEnable() { + World world = Bukkit.getWorld("Lobby"); + JRidesPlugin.setWorld(world); + + JRidesPlugin.setBukkitPluginHost(this); + ServiceProviderConfigurator.configure(this); + JRidesPlugin.initOtherStatics(); + + PlayerManager playerManager = ServiceProvider.getSingleton(PlayerManager.class); + + PluginManager pluginManager = getServer().getPluginManager(); + pluginManager.registerEvents(new BukkitPlayerJoinEventListener(), this); + pluginManager.registerEvents(new PlayerManagerListener(playerManager), this); + pluginManager.registerEvents(new ViewportListener( + ServiceProvider.getSingleton(ViewportManager.class), + playerManager), this); + pluginManager.registerEvents(new ButtonClickEventListener(), this); + pluginManager.registerEvents(new SignMenuListener("Control panel"), this); + pluginManager.registerEvents(new RideCounterListener(), this); + pluginManager.registerEvents(new RideOverviewMapListener(), this); + pluginManager.registerEvents(new RideCounterMapListener(), this); + pluginManager.registerEvents(new MessageAgentManagerListener(), this); + pluginManager.registerEvents(new PlayerTeleportToRideListener(), this); + pluginManager.registerEvents(new RideMenuLoader(), this); + pluginManager.registerEvents(new PassengerListener(), this); + + ConfigurationSerialization.registerClass(RideCounterRecord.class); + ConfigurationSerialization.registerClass(RideCounterRecordCollection.class); + ConfigurationSerialization.registerClass(RideCounterRecordRideCollection.class); + ConfigurationSerialization.registerClass(RideState.class); + + MainCommandExecutor commandExecutor = new MainCommandExecutor(); + getServer().getPluginCommand("jrides").setTabCompleter(commandExecutor); + getServer().getPluginCommand("jrides").setExecutor(commandExecutor); + + RideManager rideManager = ServiceProvider.getSingleton(RideManager.class); + rideManager.initAllRides(world); + + ViewportManager viewportManager = ServiceProvider.getSingleton(ViewportManager.class); + + for(org.bukkit.entity.Player bukkitPlayer : world.getPlayers()){ + Player player = playerManager.getPlayer(bukkitPlayer); + getLogger().info("Initialising jrides for player " + bukkitPlayer.getName()); + viewportManager.updateVisuals(player); + } + + VirtualEntityPacketListener packetListener = ServiceProvider.getSingleton(VirtualEntityPacketListener.class); + ProtocolManager protocolManager = ServiceProvider.getSingleton(ProtocolManager.class); + protocolManager.addPacketListener(packetListener); + + SoftEjector.startClock(this); + + StartMessage.sendEnabledMessage(); + } + + @Override + public void onDisable() { + PlayerManager playerManager = ServiceProvider.getSingleton(PlayerManager.class); + ViewportManager viewportManager = ServiceProvider.getSingleton(ViewportManager.class); + RideManager rideManager = ServiceProvider.getSingleton(RideManager.class); + RideCounterManager rideCounterManager = ServiceProvider.getSingleton(RideCounterManager.class); + MenuSessionManager menuSessionManager = ServiceProvider.getSingleton(MenuSessionManager.class); + + for(Player player : playerManager.getPlayers()){ + player.clearSmoothAnimationRotation(); + } + + menuSessionManager.closeAllOpenMenus(); + rideManager.unloadAllRides(); + viewportManager.despawnAll(); + rideCounterManager.saveAndUnloadAll(); + + StartMessage.sendDisabledMessage(); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/AbstractRideHandle.java b/src/main/java/com/jverbruggen/jrides/animator/AbstractRideHandle.java new file mode 100644 index 00000000..dc9e9378 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/AbstractRideHandle.java @@ -0,0 +1,199 @@ +package com.jverbruggen.jrides.animator; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.config.coaster.objects.SoundsConfig; +import com.jverbruggen.jrides.config.ride.RideCounterMapConfigs; +import com.jverbruggen.jrides.config.ride.RideState; +import com.jverbruggen.jrides.control.controller.RideController; +import com.jverbruggen.jrides.event.ride.RideStateUpdatedEvent; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.language.LanguageFileTag; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.menu.Menu; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.ride.Ride; +import com.jverbruggen.jrides.models.ride.count.RideCounterRecord; +import org.bukkit.Sound; +import org.bukkit.World; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; + +public abstract class AbstractRideHandle implements RideHandle{ + private World world; + private Ride ride; + private RideState rideState; + private boolean loaded; + private Menu rideControlMenu; + private RideController rideController; + private final SoundsConfig sounds; + private final PlayerLocation customEjectLocation; + + private List topRideCounters; + private RideCounterMapConfigs rideCounterMapConfigs; + + public AbstractRideHandle(World world, Ride ride, RideState rideState, boolean loaded, SoundsConfig sounds, PlayerLocation customEjectLocation, RideCounterMapConfigs rideCounterMapConfigs) { + this.world = world; + this.ride = ride; + this.rideState = rideState; + this.loaded = loaded; + this.customEjectLocation = customEjectLocation; + this.rideController = null; + this.topRideCounters = new ArrayList<>(); + + this.sounds = sounds; + this.rideCounterMapConfigs = rideCounterMapConfigs; + } + + public World getWorld() { + return world; + } + + @Override + public Ride getRide() { + return ride; + } + + @Override + public RideState getState() { + return rideState; + } + + @Override + public PlayerLocation getCustomEjectLocation() { + return customEjectLocation; + } + + @Override + public void setState(RideState state) { + assert state != null; + + this.rideState = state; + RideStateUpdatedEvent.send(ride, rideState); + } + + @Override + public void unload(boolean save) { + if(!loaded) return; + if(save) rideState.save(); + loaded = false; + JRidesPlugin.getLogger().info("Unloaded ride " + getRide().getDisplayName()); + } + + @Override + public boolean isLoaded() { + return loaded; + } + + + @Override + public void broadcastRideOpen() { + JRidesPlugin.getLanguageFile().sendMessage( + JRidesPlugin.getBroadcastReceiver(), + LanguageFileField.NOTIFICATION_RIDE_STATE_OPEN, + b -> b.add(LanguageFileTag.rideDisplayName, getRide().getDisplayName())); + } + + @Override + public void broadcastRideClose() { + JRidesPlugin.getLanguageFile().sendMessage( + JRidesPlugin.getBroadcastReceiver(), + LanguageFileField.NOTIFICATION_RIDE_STATE_CLOSED, + b -> b.add(LanguageFileTag.rideDisplayName, getRide().getDisplayName())); + } + + @Override + public void open(Player authority) { + if(!authority.hasPermission(Permissions.ELEVATED_RIDE_OPEN_STATE_CHANGE)){ + JRidesPlugin.getLanguageFile().sendMessage(authority, LanguageFileField.ERROR_GENERAL_NO_PERMISSION_MESSAGE); + return; + } + + boolean opened = getState().setStateOpened(this); + if(opened) authority.playSound(Sound.BLOCK_FENCE_GATE_OPEN); + else authority.playSound(Sound.UI_BUTTON_CLICK); + } + + @Override + public void close(Player authority) { + if(!authority.hasPermission(Permissions.ELEVATED_RIDE_OPEN_STATE_CHANGE)){ + JRidesPlugin.getLanguageFile().sendMessage(authority, LanguageFileField.ERROR_GENERAL_NO_PERMISSION_MESSAGE); + return; + } + + attemptClose(authority); + } + + private boolean attemptClose(@Nullable Player authority){ + if(authority != null && !authority.hasPermission(Permissions.ELEVATED_RIDE_OPEN_STATE_CHANGE)){ + JRidesPlugin.getLanguageFile().sendMessage(authority, LanguageFileField.ERROR_GENERAL_NO_PERMISSION_MESSAGE); + return false; + } + + if(getState().getOpenState().isOpen()){ + boolean closed = getState().setStateClosed(this); + + if(authority != null){ + if(!closed){ + authority.playSound(Sound.UI_BUTTON_CLICK); + }else{ + authority.playSound(Sound.BLOCK_FENCE_GATE_CLOSE); + } + } + } + + Player currentOperator = getRideController().getOperator(); + if(currentOperator != null) currentOperator.setOperating(null); + getRideControlMenu().sendUpdate(); + + if(getState().getOpenState().isClosing()){ + if(canFullyClose()){ + getState().setStateFullyClosed(); + }else return false; + } + + return true; + } + + @Override + public RideController getRideController() { + return rideController; + } + + @Override + public void setRideController(RideController rideController, Menu rideControlMenu) { + this.rideController = rideController; + this.rideControlMenu = rideControlMenu; + } + + @Override + public Menu getRideControlMenu() { + return rideControlMenu; + } + + @Override + public List getTopRideCounters() { + return topRideCounters; + } + + public SoundsConfig getSounds() { + return sounds; + } + + + @Override + public boolean isOpen() { + return isLoaded() && getState().getOpenState().isOpen(); + } + + @Override + public boolean canFullyClose() { + return getPassengers().isEmpty(); + } + + public RideCounterMapConfigs getRideCounterMapConfigs() { + return rideCounterMapConfigs; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/RideHandle.java b/src/main/java/com/jverbruggen/jrides/animator/RideHandle.java new file mode 100644 index 00000000..f9719f84 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/RideHandle.java @@ -0,0 +1,51 @@ +package com.jverbruggen.jrides.animator; + +import com.jverbruggen.jrides.config.coaster.objects.SoundsConfig; +import com.jverbruggen.jrides.config.ride.RideState; +import com.jverbruggen.jrides.control.controller.RideController; +import com.jverbruggen.jrides.control.trigger.DispatchTrigger; +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.menu.Menu; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.ride.Ride; +import com.jverbruggen.jrides.models.ride.StationHandle; +import com.jverbruggen.jrides.models.ride.count.RideCounterRecord; + +import javax.annotation.Nonnull; +import java.util.List; + +public interface RideHandle { + void tick(); + Ride getRide(); + RideController getRideController(); + Menu getRideControlMenu(); + PlayerLocation getCustomEjectLocation(); + + void setRideController(RideController rideController, Menu rideControlMenu); + DispatchTrigger getDispatchTrigger(); + TriggerContext getTriggerContext(@Nonnull String contextOwner); + TriggerContext getFirstTriggerContext(); + + PlayerLocation getEjectLocation(); + List getStationHandles(); + + List getTopRideCounters(); + List getPassengers(); + + void setState(RideState state); + RideState getState(); + boolean isOpen(); + + void open(Player authority); + void close(Player authority); + boolean canFullyClose(); + + void broadcastRideOpen(); + void broadcastRideClose(); + + void unload(boolean save); + boolean isLoaded(); + + SoundsConfig getSounds(); +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/animatedjava/AnimatedJavaExecutor.java b/src/main/java/com/jverbruggen/jrides/animator/animatedjava/AnimatedJavaExecutor.java new file mode 100644 index 00000000..b5263c5f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/animatedjava/AnimatedJavaExecutor.java @@ -0,0 +1,79 @@ +package com.jverbruggen.jrides.animator.animatedjava; + +import com.jverbruggen.jrides.models.math.Vector3; +import org.bukkit.Bukkit; + +public class AnimatedJavaExecutor { + private final String rootEntityTag; + private final String rigName; + private final Vector3 location; + private boolean isSpawned; + + public AnimatedJavaExecutor(String rootEntityTag, String rigName, Vector3 location) { + this.rootEntityTag = rootEntityTag; + this.rigName = rigName; + this.location = location; + this.isSpawned = false; + } + + public boolean isSpawned(){ + return isSpawned; + } + + public void spawnRig(){ + executeCommand(getSpawnRigCommand()); + isSpawned = true; + } + + public void playAnimation(String animationName){ + if(!isSpawned) throw new RuntimeException("Rig was not spawned"); + executeCommand(getPlayAnimationCommand(animationName)); + } + + public void removeRig(){ + executeCommand(getRemoveRigCommand()); + isSpawned = false; + } + + public void removeAllRigs(){ + executeCommand(getRemoveAllRigsCommand()); + isSpawned = false; + } + + private void executeCommand(String command){ + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command); + } + + private String getSpawnRigCommand(){ + return getRunFunctionBaseCommand() + "animated_java:" + rigName + "/summon"; + } + + private String getRemoveRigCommand(){ + return getRunFunctionAsEntityBaseCommand() + "animated_java:" + rigName + "/remove/this"; + } + + private String getRemoveAllRigsCommand(){ + return getRunFunctionBaseCommand() + "animated_java:" + rigName + "/remove/all"; + } + + private String getPlayAnimationCommand(String animationName){ + return getRunFunctionAsEntityBaseCommand() + "animated_java:" + rigName + "/animations/" + animationName + "/play"; + } + + private String getRunFunctionAsEntityBaseCommand(){ + return "execute " + + "positioned " + getLocationString() + " " + + "as @e[type=minecraft:item_display,tag=" + rootEntityTag + ",limit=1] " + + "run function "; + } + + private String getRunFunctionBaseCommand(){ + return "execute " + + "positioned " + getLocationString() + " " + + "run function "; + } + + private String getLocationString(){ + return location.getX() + " " + location.getY() + " " + location.getZ(); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/CoasterHandle.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/CoasterHandle.java new file mode 100644 index 00000000..887c5cca --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/CoasterHandle.java @@ -0,0 +1,220 @@ +package com.jverbruggen.jrides.animator.coaster; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.AbstractRideHandle; +import com.jverbruggen.jrides.animator.coaster.tool.ParticleTrackVisualisationTool; +import com.jverbruggen.jrides.config.coaster.objects.SoundsConfig; +import com.jverbruggen.jrides.config.ride.RideCounterMapConfigs; +import com.jverbruggen.jrides.control.controller.RideController; +import com.jverbruggen.jrides.control.trigger.DispatchTrigger; +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.effect.EffectTriggerCollection; +import com.jverbruggen.jrides.effect.handle.cart.CartEffectTriggerHandle; +import com.jverbruggen.jrides.effect.handle.train.TrainEffectTriggerHandle; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.ride.CoasterStationHandle; +import com.jverbruggen.jrides.models.ride.Ride; +import com.jverbruggen.jrides.models.ride.StationHandle; +import com.jverbruggen.jrides.models.ride.coaster.transfer.Transfer; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.section.Unlockable; +import org.bukkit.World; + +import javax.annotation.Nonnull; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class CoasterHandle extends AbstractRideHandle { + private Track track; + private ParticleTrackVisualisationTool visualisationTool; + private List stationHandles; + private List trains; + private final List transfers; + private final Map unlockables; + private EffectTriggerCollection trainEffectTriggerCollection; + private EffectTriggerCollection cartEffectTriggerCollection; + + private final double dragConstant; + private final double gravityConstant; + private int rideOverviewMapId; + private final RideCounterMapConfigs rideCounterMapConfigs; + + public CoasterHandle(Ride ride, World world, SoundsConfig sounds, PlayerLocation customEjectLocation, int rideOverviewMapId, boolean loaded, double dragConstant, double gravityConstant, RideCounterMapConfigs rideCounterMapConfigs) { + super(world, ride, null, loaded, sounds, customEjectLocation, rideCounterMapConfigs); + this.dragConstant = dragConstant; + this.gravityConstant = gravityConstant; + + this.trains = new ArrayList<>(); + this.stationHandles = new ArrayList<>(); + this.transfers = new ArrayList<>(); + this.unlockables = new HashMap<>(); + this.visualisationTool = null; + this.track = null; + this.trainEffectTriggerCollection = null; + this.rideOverviewMapId = rideOverviewMapId; + this.rideCounterMapConfigs = rideCounterMapConfigs; + } + + public double getDragConstant() { + return dragConstant; + } + + public double getGravityConstant() { + return gravityConstant; + } + + public int getRideOverviewMapId(){ + return this.rideOverviewMapId; + } + + public void setRideOverviewMapId(int rideOverviewMapId) { + if(rideOverviewMapId<0) throw new RuntimeException("Cannot set ride overview map id to a negative value"); + this.rideOverviewMapId = rideOverviewMapId; + } + + public void setTrains(List trains) { + this.trains = trains; + trains.forEach(t -> t.setCoasterHandle(this)); + this.visualisationTool = ParticleTrackVisualisationTool.fromTrack(getWorld(), track, 20, trains); + } + + public List getTrains() { + return trains; + } + + public void setTrack(Track track) { + this.track = track; + } + + public ParticleTrackVisualisationTool getVisualisationTool() { + return visualisationTool; + } + + @Override + public DispatchTrigger getDispatchTrigger() { + return getStationHandle(null).getTriggerContext().getDispatchTrigger(); + } + + @Override + public TriggerContext getTriggerContext(@Nonnull String contextOwner) { + CoasterStationHandle stationHandle = getStationHandle(contextOwner); + if(stationHandle == null) return null; + return stationHandle.getTriggerContext(); + } + + @Override + public TriggerContext getFirstTriggerContext() { + return getStationHandles().get(0).getTriggerContext(); + } + + @Override + public PlayerLocation getEjectLocation() { + PlayerLocation customEjectLocation = getCustomEjectLocation(); + if(customEjectLocation != null) return customEjectLocation; + + return stationHandles.stream() + .filter(s -> s.getEjectLocation() != null) + .map(StationHandle::getEjectLocation) + .findFirst().orElse(null); + } + + @Override + public List getStationHandles() { + return stationHandles.stream().map(h->(StationHandle)h).collect(Collectors.toList()); + } + + public void addStationHandle(CoasterStationHandle stationHandle) { + stationHandles.add(stationHandle); + } + + public List getCoasterStationHandles() { + return stationHandles; + } + + public CoasterStationHandle getStationHandle(String shortName){ + if(getStationHandles().size() == 0){ + JRidesPlugin.getLogger().severe("Looked for station with short name " + shortName + " but size was 0"); + return null; + } + + return stationHandles.stream() + .filter(s -> s.getShortName().equalsIgnoreCase(shortName)) + .findFirst() + .orElseThrow(() -> { + String options = stationHandles.stream().map(StationHandle::getShortName).collect(Collectors.joining(", ")); + return new RuntimeException("Station short name " + shortName + " did not exist. Existing stations: " + options); + }); + } + + public CoasterStationHandle getStationHandle(int index){ + if(getStationHandles().size() <= index) return null; + return getCoasterStationHandles().get(index); + } + + public boolean hasStation(){ + return getStationHandles().size() > 0; + } + + public void tick(){ + if(!isLoaded()) return; + + RideController rideController = getRideController(); + if(rideController.isActive()) + rideController.getControlMode().tick(); + + for(TrainHandle trainHandle : trains){ + trainHandle.tick(); + } + for(Transfer transfer : transfers){ + transfer.tick(); + } + } + + public EffectTriggerCollection getTrainEffectTriggerCollection() { + return trainEffectTriggerCollection; + } + + public void setTrainEffectTriggerCollection(EffectTriggerCollection trainEffectTriggerCollection) { + this.trainEffectTriggerCollection = trainEffectTriggerCollection; + } + + public EffectTriggerCollection getCartEffectTriggerCollection() { + return cartEffectTriggerCollection; + } + + public void setCartEffectTriggerCollection(EffectTriggerCollection cartEffectTriggerCollection) { + this.cartEffectTriggerCollection = cartEffectTriggerCollection; + } + + public void addTransfer(Transfer transfer){ + transfers.add(transfer); + } + + public List getTransfers() { + return transfers; + } + + public void addUnlockable(String identifier, Unlockable unlockable){ + unlockables.put(identifier, unlockable); + } + + public Unlockable getUnlockable(String identifier){ + return unlockables.get(identifier); + } + + public Track getTrack(){ + return track; + } + + @Override + public List getPassengers() { + return getTrains().stream() + .flatMap(trainHandle -> trainHandle.getTrain().getPassengers().stream()) + .toList(); + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/EffectHandler.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/EffectHandler.java new file mode 100644 index 00000000..d723e262 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/EffectHandler.java @@ -0,0 +1,137 @@ +package com.jverbruggen.jrides.animator.coaster; + +import com.jverbruggen.jrides.effect.EffectTriggerCollection; +import com.jverbruggen.jrides.effect.handle.EffectTriggerHandle; +import com.jverbruggen.jrides.effect.handle.cart.CartEffectTriggerHandle; +import com.jverbruggen.jrides.effect.handle.train.TrainEffectTriggerHandle; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.train.CoasterCart; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map; + +public class EffectHandler { + private final Train train; + private CoasterHandle coasterHandle; + + private boolean hasEffects; + private TrainEffectTriggerHandle nextEffect; + + private boolean hasCartEffects; + private final Map nextCartEffects; + + public EffectHandler(Train train, Map nextCartEffects) { + this.train = train; + this.coasterHandle = null; + this.hasEffects = false; + this.nextEffect = null; + this.hasCartEffects = false; + this.nextCartEffects = nextCartEffects; + } + + public void setCoasterHandle(CoasterHandle coasterHandle){ + this.coasterHandle = coasterHandle; + + EffectTriggerCollection trainEffectTriggerCollection = coasterHandle.getTrainEffectTriggerCollection(); + if(trainEffectTriggerCollection != null && trainEffectTriggerCollection.size() > 0){ + hasEffects = true; + } + + EffectTriggerCollection cartEffectTriggerCollection = coasterHandle.getCartEffectTriggerCollection(); + if(cartEffectTriggerCollection != null && cartEffectTriggerCollection.size() > 0){ + hasCartEffects = true; + } + + if(hasEffects || hasCartEffects) + resetEffectsRandomPos(); + } + + private void resetEffectsRandomPos(){ + if(hasEffects){ + nextEffect = EffectTriggerHandle.FindNearestNextEffect( + TrainEffectTriggerHandle.class, + coasterHandle.getTrainEffectTriggerCollection().getLinkedList(), + train.getHeadOfTrainFrame()); + +// Bukkit.broadcastMessage("Next train effect: " + nextEffect.getFrame()); + } + + if(hasCartEffects){ + LinkedList cartEffectLinkedList = coasterHandle.getCartEffectTriggerCollection().getLinkedList(); + + for(CoasterCart cart : train.getCarts()){ + CartEffectTriggerHandle nextCartEffect = EffectTriggerHandle.FindNearestNextEffect( + CartEffectTriggerHandle.class, + cartEffectLinkedList, + cart.getFrame() + ); + nextCartEffects.put(cart, nextCartEffect); + +// Bukkit.broadcastMessage("Next cart effect: " + nextCartEffect.getFrame()); + } + } + } + + public void resetEffects(){ + if(hasEffects){ + nextEffect = coasterHandle.getTrainEffectTriggerCollection().first(); + } + + if(hasCartEffects){ + LinkedList cartEffectLinkedList = coasterHandle.getCartEffectTriggerCollection().getLinkedList(); + + for(CoasterCart cart : train.getCarts()){ + CartEffectTriggerHandle nextCartEffect = cartEffectLinkedList.get(0); + nextCartEffects.put(cart, nextCartEffect); + } + } + } + + private boolean shouldTrainEffect(TrainEffectTriggerHandle trainEffectTriggerHandle, Frame currentFrame){ + return trainEffectTriggerHandle.shouldPlay(currentFrame); + } + + public void playTrainEffects(Frame currentFrame){ + while(nextEffect != null){ + if(!shouldTrainEffect(nextEffect, currentFrame)) break; + boolean processNext = nextEffect.executeForTrain(train); + if(!processNext) break; + + nextEffect = nextEffect.next(); + } + } + + private boolean shouldCartEffectPlay(CartEffectTriggerHandle cartEffectTriggerHandle, Frame currentFrame){ + return cartEffectTriggerHandle.shouldPlay(currentFrame); + } + + public void playCartEffects(CoasterCart cart){ + Frame currentCartFrame = cart.getFrame(); + CartEffectTriggerHandle nextCartEffect = nextCartEffects.get(cart); + while(nextCartEffect != null){ + if(!shouldCartEffectPlay(nextCartEffect, currentCartFrame)) break; + boolean processNext = nextCartEffect.executeForCart(cart); + if(!processNext) break; + + CartEffectTriggerHandle newNextEffect = nextCartEffect.next(); + nextCartEffects.put(cart, newNextEffect); + nextCartEffect = newNextEffect; + } + } + + public static EffectHandler createForTrain(Train train){ + Map nextCartEffects = new HashMap<>(); + + for(CoasterCart cart : train.getCarts()){ + nextCartEffects.put(cart, null); + } + + return new EffectHandler(train, nextCartEffects); + } + + public boolean hasCartEffects() { + return hasCartEffects; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/NoLimitsExportPositionRecord.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/NoLimitsExportPositionRecord.java new file mode 100644 index 00000000..56d221a0 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/NoLimitsExportPositionRecord.java @@ -0,0 +1,120 @@ +package com.jverbruggen.jrides.animator.coaster; + +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import org.bukkit.util.Vector; + +public class NoLimitsExportPositionRecord { + private final int index; + private final float posX; + private final float posY; + private final float posZ; + private final float frontX; + private final float frontY; + private final float frontZ; + private final float leftX; + private final float leftY; + private final float leftZ; + private final float upX; + private final float upY; + private final float upZ; + private final Quaternion orientation; + + public NoLimitsExportPositionRecord(int index, float posX, float posY, float posZ, float frontX, float frontY, float frontZ, float leftX, float leftY, float leftZ, float upX, float upY, float upZ) { + this.index = index; + this.posX = posX; + this.posY = posY; + this.posZ = posZ; + this.frontX = frontX; + this.frontY = frontY; + this.frontZ = frontZ; + this.leftX = leftX; + this.leftY = leftY; + this.leftZ = leftZ; + this.upX = upX; + this.upY = upY; + this.upZ = upZ; + + Vector dirVector = new Vector(leftX, leftY, leftZ).multiply(-1); + Vector upVector = new Vector(upX, upY, upZ); + this.orientation = Quaternion.fromLookDirection(dirVector, upVector); + } + + public int getIndex() { + return index; + } + + public float getPosX() { + return posX; + } + + public float getPosY() { + return posY; + } + + public float getPosZ() { + return posZ; + } + + public float getFrontX() { + return frontX; + } + + public float getFrontY() { + return frontY; + } + + public float getFrontZ() { + return frontZ; + } + + public float getLeftX() { + return leftX; + } + + public float getLeftY() { + return leftY; + } + + public float getLeftZ() { + return leftZ; + } + + public float getUpX() { + return upX; + } + + public float getUpY() { + return upY; + } + + public float getUpZ() { + return upZ; + } + + public Quaternion getOrientation() { + return orientation; + } + + public Vector3 toVector3(){ + return new Vector3(posX, posY, posZ); + } + + public static NoLimitsExportPositionRecord createFromCSVAttributes(String[] attributes, int index,float offsetX, float offsetY, float offsetZ){ + return new NoLimitsExportPositionRecord( + index, + Float.parseFloat(attributes[1]) + offsetX, + Float.parseFloat(attributes[2]) + offsetY, + Float.parseFloat(attributes[3]) + offsetZ, + Float.parseFloat(attributes[4]), + Float.parseFloat(attributes[5]), + Float.parseFloat(attributes[6]), + Float.parseFloat(attributes[7]), + Float.parseFloat(attributes[8]), + Float.parseFloat(attributes[9]), + Float.parseFloat(attributes[10]), + Float.parseFloat(attributes[11]), + Float.parseFloat(attributes[12]) + ); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/TrainHandle.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/TrainHandle.java new file mode 100644 index 00000000..8a33f32e --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/TrainHandle.java @@ -0,0 +1,158 @@ +package com.jverbruggen.jrides.animator.coaster; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.TrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.CartMovement; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.CartMovementFactory; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.TrainMovement; +import com.jverbruggen.jrides.logging.LogType; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.Speed; +import com.jverbruggen.jrides.models.properties.TrainEnd; +import com.jverbruggen.jrides.models.ride.coaster.train.CoasterCart; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.provider.SectionProvider; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.SoundCategory; + +import java.util.Map; +import java.util.Set; + +public class TrainHandle { + private final Train train; + private final Track track; + private final Speed speedBPS; + private TrackBehaviour trackBehaviour; + private final SectionProvider sectionProvider; + private final CartMovementFactory cartMovementFactory; + private CoasterHandle coasterHandle; + + private final EffectHandler effectHandler; + + private final int windSoundInterval; + private int windSoundState; + + public TrainHandle(SectionProvider sectionProvider, Train train, Track track) { + this.sectionProvider = sectionProvider; + this.cartMovementFactory = ServiceProvider.getSingleton(CartMovementFactory.class); + this.train = train; + this.track = track; + this.trackBehaviour = train.getHeadSection().getTrackBehaviour(); + this.speedBPS = new Speed(0); + this.coasterHandle = null; + this.effectHandler = EffectHandler.createForTrain(train); + + this.train.setHandle(this); + + this.windSoundInterval = 4; + this.windSoundState = 0; + } + + public void tick(){ + if(train.isCrashed()) return; + + // --- Calculate movement that should be applied to the train + TrainMovement result = trackBehaviour.move(speedBPS, this, train.getHeadSection()); + if(result == null) return; + + // --- Apply movement: new head frame and speed + speedBPS.setSpeed(result.getNewSpeed().getSpeedPerTick()); + + // --- Move carts according to instructions + Set> cartMovements = cartMovementFactory.createOnTrackCartMovement(train.getHandle(), train.getCarts(), result.getNewSpeed().getFrameIncrement(), null).entrySet(); + if(cartMovements != null){ + for(Map.Entry cartMovement : cartMovements){ + CoasterCart cart = cartMovement.getKey(); + CartMovement movement = cartMovement.getValue(); + cart.setPosition(movement); + cart.playEffects(); + } + } + + Frame trainHeadOfTrainFrame = train.getHeadOfTrainFrame(); + Frame trainMiddleOfTrainFrame = train.getMiddleOfTrainFrame(); + Frame trainTailOfTrainFrame = train.getTailOfTrainFrame(); + + boolean headAppliesBehaviour = speedBPS.isGoingForwards(); + boolean tailAppliesBehaviour = !headAppliesBehaviour; + + // Both Head and Tail update section occupations: if going forwards: head locks next and tail unlocks previous + sectionProvider.addFramesWithSectionLogic(this, trainHeadOfTrainFrame, result.getNewHeadOfTrainFrame().getValue(), + true, TrainEnd.HEAD, "HEAD", headAppliesBehaviour); + sectionProvider.addFramesWithSectionLogic(this, trainMiddleOfTrainFrame, result.getNewMiddleOfTrainFrame().getValue()); + sectionProvider.addFramesWithSectionLogic(this, trainTailOfTrainFrame, result.getNewTailOfTrainFrame().getValue(), + true, TrainEnd.TAIL, "TAIL", tailAppliesBehaviour); + + JRidesPlugin.getLogger().info(LogType.SECTIONS_DETAIL, trainHeadOfTrainFrame + " -= " + + trainMiddleOfTrainFrame + " =- " + trainTailOfTrainFrame); + + // --- Set new train location according to new frames + Vector3 headLocation = track.getLocationFor(trainHeadOfTrainFrame); + Vector3 middleLocation = track.getLocationFor(trainMiddleOfTrainFrame); + Vector3 tailLocation = track.getLocationFor(trainTailOfTrainFrame); + train.setCurrentLocation(headLocation, middleLocation, tailLocation); + + sendPositionUpdatesToListeners("HEAD", trainHeadOfTrainFrame); + sendPositionUpdatesToListeners("MIDD", trainMiddleOfTrainFrame); + sendPositionUpdatesToListeners("TAIL", trainTailOfTrainFrame); + train.sendPositionMessage("SPEED: " + speedBPS); + + effectHandler.playTrainEffects(trainHeadOfTrainFrame); + if(effectHandler.hasCartEffects()){ + for(CoasterCart cart : train.getCarts()){ + effectHandler.playCartEffects(cart); + } + } + playWindSounds(); + } + + private void sendPositionUpdatesToListeners(String identifier, Frame currentFrame) { + train.sendPositionMessage(identifier + ": " + currentFrame.toString()); + } + + + private void playWindSounds(){ + String sound = coasterHandle.getSounds().getOnrideWind(); + if(sound == null) return; + if(windSoundState < windSoundInterval) + windSoundState++; + else{ + for(Player player : train.getPassengers()){ + float pitch = (float)Math.abs(speedBPS.getSpeedPerTick() / 10) + 0.4f; + float volume = Math.abs((pitch - 0.3f) / 5) - 0.05f; + player.getBukkitPlayer().playSound(player.getBukkitPlayer().getLocation(), + sound, SoundCategory.MASTER, volume, pitch); + } + windSoundState = 0; + } + } + + public Train getTrain() { + return train; + } + + public void setCoasterHandle(CoasterHandle coasterHandle) { + this.coasterHandle = coasterHandle; + + this.effectHandler.setCoasterHandle(coasterHandle); + } + + public CoasterHandle getCoasterHandle() { + return coasterHandle; + } + + public Speed getSpeed() { + return speedBPS; + } + + public void setTrackBehaviour(TrackBehaviour trackBehaviour) { + this.trackBehaviour = trackBehaviour; + } + + public void resetEffects() { + effectHandler.resetEffects(); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/tool/ParticleTrackVisualisationTool.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/tool/ParticleTrackVisualisationTool.java new file mode 100644 index 00000000..6f1b58a4 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/tool/ParticleTrackVisualisationTool.java @@ -0,0 +1,69 @@ +package com.jverbruggen.jrides.animator.coaster.tool; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.CoasterCart; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.World; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +public class ParticleTrackVisualisationTool extends ParticleVisualisationTool { + private List locations; + private World world; + private List sectionSplitLocations; + private List trains; + + public ParticleTrackVisualisationTool(World world, List locations, List sectionSplitLocations, List trains){ + super(5); + this.world = world; + this.locations = locations; + this.sectionSplitLocations = sectionSplitLocations; + this.trains = trains; + } + + public static ParticleTrackVisualisationTool fromTrack(World world, Track track, int takeOneInX, List trains){ + List positions = track.getAllPositions(); + + List sectionSplitLocations = track.getSections().stream() + .map(s -> s.getParentTrack().getLocationFor(s.getEndFrame()).toBukkitLocation(world)) + .collect(Collectors.toList()); + + List locations = IntStream + .range(0, positions.size()) + .filter(i -> i % takeOneInX == 0) + .mapToObj(i -> positions.get(i).toBukkitLocation(world)) + .collect(Collectors.toList()); + + return new ParticleTrackVisualisationTool(world, locations, sectionSplitLocations, trains); + } + + @Override + public void tick(){ + for(Player viewer : getViewers()){ + spawnVisualisationParticles(viewer); + } + } + + public void spawnVisualisationParticles(Player player){ + org.bukkit.entity.Player bukkitPlayer = player.getBukkitPlayer(); + for(Location location : locations){ + bukkitPlayer.spawnParticle(Particle.VILLAGER_HAPPY, location, 1, 0.01, 0.01, 0.01, 0); + } + for(Location splitSectionLocation : sectionSplitLocations){ + bukkitPlayer.spawnParticle(Particle.CRIT_MAGIC, splitSectionLocation, 5, 0.01, 1, 0.01, 0); + } + for(TrainHandle train : trains){ + bukkitPlayer.spawnParticle(Particle.DRIP_WATER, train.getTrain().getCurrentHeadLocation().toBukkitLocation(world), 5, 0.01, 1, 0.01, 0); + for(CoasterCart cart : train.getTrain().getCarts()){ + bukkitPlayer.spawnParticle(Particle.VILLAGER_HAPPY, cart.getPosition().toBukkitLocation(world), 5, 0.01, 1, 0.01, 0); + } + bukkitPlayer.spawnParticle(Particle.DRIP_LAVA, train.getTrain().getCurrentTailLocation().toBukkitLocation(world), 5, 0.01, 1, 0.01, 0); + } + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/tool/ParticleTrainVisualisationTool.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/tool/ParticleTrainVisualisationTool.java new file mode 100644 index 00000000..da10502b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/tool/ParticleTrainVisualisationTool.java @@ -0,0 +1,29 @@ +package com.jverbruggen.jrides.animator.coaster.tool; + +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import org.bukkit.Particle; +import org.bukkit.World; + +public class ParticleTrainVisualisationTool extends ParticleVisualisationTool { + private World world; + private Train train; + + public ParticleTrainVisualisationTool(World world, Train train){ + super(5); + this.world = world; + this.train = train; + } + + @Override + public void tick(){ + for(Player viewer : getViewers()){ + spawnVisualisationParticles(viewer); + } + } + + public void spawnVisualisationParticles(Player player){ + org.bukkit.entity.Player bukkitPlayer = player.getBukkitPlayer(); + bukkitPlayer.spawnParticle(Particle.VILLAGER_HAPPY, train.getCurrentHeadLocation().toBukkitLocation(world), 1, 0.01, 0.01, 0.01, 0); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/tool/ParticleVisualisationTool.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/tool/ParticleVisualisationTool.java new file mode 100644 index 00000000..f79fa6a2 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/tool/ParticleVisualisationTool.java @@ -0,0 +1,56 @@ +package com.jverbruggen.jrides.animator.coaster.tool; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.models.entity.Player; +import org.bukkit.Bukkit; + +import java.util.ArrayList; +import java.util.List; + +public abstract class ParticleVisualisationTool { + private List viewers; + private int taskId; + private int interval; + + public abstract void tick(); + + public ParticleVisualisationTool(int interval) { + this.viewers = new ArrayList<>(); + this.taskId = -1; + this.interval = interval; + } + + public List getViewers() { + return viewers; + } + + public void addViewer(Player player){ + viewers.add(player); + + if(taskId == -1) runNewTask(); + } + + public void removeViewer(Player player){ + viewers.remove(player); + + if(viewers.size() == 0) cancelTask(); + } + + public boolean isViewer(Player player){ + return viewers.contains(player); + } + + private void runNewTask(){ + if(taskId == -1){ + taskId = Bukkit.getScheduler().runTaskTimer(JRidesPlugin.getBukkitPlugin(), this::tick, interval, interval).getTaskId(); + }else throw new RuntimeException("Task set moment unexpected"); + } + + private void cancelTask(){ + if(taskId != -1){ + Bukkit.getScheduler().cancelTask(taskId); + taskId = -1; + }else throw new RuntimeException("Task cancel moment unexpected"); + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/BaseTrackBehaviour.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/BaseTrackBehaviour.java new file mode 100644 index 00000000..bff22a11 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/BaseTrackBehaviour.java @@ -0,0 +1,158 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour; + +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.CartMovementFactory; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.TrainMovement; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.Speed; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.Section; +import com.jverbruggen.jrides.models.ride.section.reference.SectionReference; +import com.jverbruggen.jrides.models.ride.section.result.BlockSectionSafetyResult; + +import java.util.Collection; +import java.util.List; +import java.util.Map; + +public abstract class BaseTrackBehaviour implements TrackBehaviour { + protected final CartMovementFactory cartMovementFactory; + protected Track parentTrack; + + protected BaseTrackBehaviour(CartMovementFactory cartMovementFactory) { + this.cartMovementFactory = cartMovementFactory; + this.parentTrack = null; + } + + protected BlockSectionSafetyResult getNextSectionSafety(Train train){ + Section nextSection = train.getNextSection(); + if(nextSection == null) return new BlockSectionSafetyResult(false, train, "No next section present"); + return nextSection.getBlockSectionSafety(train); + } + + protected boolean shouldReserveNextSection(Train train){ + Section nextSection = train.getNextSection(); + if(nextSection == null) return false; + return nextSection.getReservedBy() != train; + } + + protected TrainMovement calculateTrainMovement(Train train, Section section, Speed speed){ + if(speed.isZero()){ + return new TrainMovement(speed, train.getHeadOfTrainFrame(), train.getMiddleOfTrainFrame(), train.getTailOfTrainFrame(), train.getCurrentLocation(), null); + } + + int speedFrameIncrement = speed.getFrameIncrement(); + + Frame newHeadOfTrainFrame = train.getHeadOfTrainFrame().clone().add(speedFrameIncrement); + Frame newMiddleOfTrainFrame = train.getMiddleOfTrainFrame().clone().add(speedFrameIncrement); + Frame newTailOfTrainFrame = train.getTailOfTrainFrame().clone().add(speedFrameIncrement); + + Vector3 newTrainLocation = newMiddleOfTrainFrame.getSection().getLocationFor(newMiddleOfTrainFrame); + + + return new TrainMovement(speed, newHeadOfTrainFrame, newMiddleOfTrainFrame, newTailOfTrainFrame, newTrainLocation, null); + } + + protected abstract void setParentTrackOnFrames(Track parentTrack); + + @Override + public void setParentTrack(Track parentTrack) { + this.parentTrack = parentTrack; + setParentTrackOnFrames(parentTrack); + } + + @Override + public Track getParentTrack() { + return parentTrack; + } + + @Override + public Section getSectionAtEnd(Train train, boolean process) { + return null; + } + + @Override + public Section getSectionAtStart(Train train, boolean process) { + return null; + } + + @Override + public void trainPassed(Train train) { + + } + + @Override + public boolean definesNextSection() { + return false; + } + + @Override + public Vector3 getBehaviourDefinedPosition(Vector3 originalPosition) { + return originalPosition; + } + + @Override + public Quaternion getBehaviourDefinedOrientation(Quaternion originalOrientation) { + return originalOrientation; + } + + @Override + public boolean accepts(Train train) { + return true; + } + + @Override + public Section getSectionNext(Train train, boolean process) { + return getSectionAtEnd(train, process); + } + + @Override + public Section getSectionPrevious(Train train, boolean process) { + return getSectionAtStart(train, process); + } + + @Override + public Collection
getAllNextSections(Train train) { + return List.of(getSectionNext(train, false)); + } + + @Override + public Collection
getAllPreviousSections(Train train) { + return List.of(getSectionPrevious(train, false)); + } + + @Override + public void populateSectionReferences(Map sectionMap) { + } + + @Override + public boolean definesNextAccepting() { + return false; + } + + @Override + public Section acceptAsNext(Train train, boolean canProcessPassed) { + return null; + } + + @Override + public boolean canHandleBlockSectionSafety() { + return false; + } + + @Override + public boolean canHandleConnections() { + return false; + } + + @Override + public boolean nextConnectsToStart() { + return true; + } + + @Override + public boolean previousConnectsToStart() { + return false; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/FreeMovementTrackBehaviour.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/FreeMovementTrackBehaviour.java new file mode 100644 index 00000000..ecfcd7a6 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/FreeMovementTrackBehaviour.java @@ -0,0 +1,99 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.CartMovementFactory; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.TrainMovement; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.Speed; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.Section; + +import javax.annotation.Nullable; + +public class FreeMovementTrackBehaviour extends BaseTrackBehaviour { + private final double gravityConstant; + private final double dragConstant; + + public FreeMovementTrackBehaviour(CartMovementFactory cartMovementFactory, double gravityConstant, double dragConstant) { + super(cartMovementFactory); + + this.gravityConstant = gravityConstant; + this.dragConstant = dragConstant; + } + + public TrainMovement move(Speed currentSpeed, TrainHandle trainHandle, Section section) { + Train train = trainHandle.getTrain(); + Speed newSpeed = calculateGravityActedSpeed(trainHandle, section, currentSpeed, gravityConstant, dragConstant); + + return calculateTrainMovement(train, section, newSpeed); + } + + @Override + public void trainExitedAtStart(@Nullable Train train, @Nullable Section section) { + + } + + @Override + public void trainExitedAtEnd(@Nullable Train train, @Nullable Section section) { + + } + + @Override + public String getName() { + return "FreeMovement"; + } + + @Override + public boolean canBlock() { + return false; + } + + @Override + public boolean canSpawnOn() { + return false; + } + + @Override + public Frame getSpawnFrame() { + return null; + } + + @Override + protected void setParentTrackOnFrames(Track parentTrack) { + + } + + private static double getGravityPitch(Train train, Vector3 newHeadOfTrainLocation, Vector3 newTailOfTrainLocation){ + if(train.getCarts().size() == 1){ + int forwardsMulti = -1; + if(!train.isFacingForwards()) + forwardsMulti = 1; + return forwardsMulti * train.getCarts().get(0).getOrientation().getRoll(); + }else{ + Vector3 headTailDifference = Vector3.subtract(newHeadOfTrainLocation, newTailOfTrainLocation); + return Quaternion.fromLookDirection(headTailDifference.toBukkitVector()).getPitch(); + } + } + + public static Speed calculateGravityActedSpeed(TrainHandle trainHandle, Section section, Speed currentSpeed, double gravityConstant, double dragConstant){ + // --- New mass middle calculation + Train train = trainHandle.getTrain(); + Section backFacingSection = train.getBackFacingTrainFrame().getSection(); + Vector3 newForwardsFacingFrameLocation = section.getLocationFor(train.getFrontFacingTrainFrame()); + Vector3 newBackwardsFacingFrameLocation = backFacingSection.getLocationFor(train.getBackFacingTrainFrame()); + + // --- Gravity speed calculation + Speed newSpeed = currentSpeed.clone(); + double pitch = getGravityPitch(train, newForwardsFacingFrameLocation, newBackwardsFacingFrameLocation); + + double dy = Math.sin(pitch/180*3.141592); + + newSpeed.add(dy * gravityConstant); + newSpeed.multiply(dragConstant); + + return newSpeed; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/LaunchTrackBehaviour.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/LaunchTrackBehaviour.java new file mode 100644 index 00000000..67a753a0 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/LaunchTrackBehaviour.java @@ -0,0 +1,169 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.CartMovementFactory; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.TrainMovement; +import com.jverbruggen.jrides.effect.handle.train.TrainEffectTriggerHandle; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.Speed; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.Section; + +import javax.annotation.Nullable; +import java.util.List; + +public class LaunchTrackBehaviour extends BaseTrackBehaviour { + private final boolean canSpawn; + private final double deceleration; + private final double acceleration; + private final double driveSpeed; + private final boolean forwardsLaunch; + + private final int waitTicks; + private final Frame engageFrame; + private final double launchAcceleration; + private final double launchSpeed; + private final double launchSpeedBackward; + private final List launchEffectTriggers; + + private int waitTicksState; + private LaunchPhase phase; + + public LaunchTrackBehaviour(CartMovementFactory cartMovementFactory, boolean canSpawn, double driveSpeed, double deceleration, double acceleration, boolean forwardsLaunch, int waitTicks, Frame engageFrame, double launchAcceleration, double launchSpeed, double launchSpeedBackward, List launchEffectTriggers) { + super(cartMovementFactory); + this.canSpawn = canSpawn; + this.deceleration = deceleration; + this.acceleration = acceleration; + this.driveSpeed = driveSpeed; + this.forwardsLaunch = forwardsLaunch; + this.waitTicks = waitTicks; + this.engageFrame = engageFrame; + this.launchSpeed = launchSpeed; + this.launchAcceleration = launchAcceleration; + this.launchSpeedBackward = launchSpeedBackward; + this.launchEffectTriggers = launchEffectTriggers; + + this.phase = LaunchPhase.IDLE; + this.waitTicksState = 0; + } + + @Override + public TrainMovement move(Speed currentSpeed, TrainHandle trainHandle, Section section) { + Speed newSpeed = currentSpeed.clone(); + Train train = trainHandle.getTrain(); + + boolean goIntoSwitch = true; + while(goIntoSwitch) { + goIntoSwitch = false; + switch (this.phase) { + case IDLE: + if(waitTicks < 0 && getNextSectionSafety(train).safe()){ + train.getNextSection().setEntireBlockReservation(train); + this.phase = LaunchPhase.LAUNCHING; + }else{ + this.phase = LaunchPhase.DRIVING; + } + + goIntoSwitch = true; + break; + case DRIVING: + if (train.getHeadSection().hasPassed(engageFrame, train.getHeadOfTrainFrame())) { + this.phase = LaunchPhase.STOPPING; + goIntoSwitch = true; + }else{ + newSpeed.approach(acceleration, deceleration, driveSpeed); + } + break; + case STOPPING: + if(newSpeed.isZero()){ + phase = LaunchPhase.WAITING; + goIntoSwitch = true; + } + newSpeed.minus(deceleration, 0); + break; + case WAITING: + if(getNextSectionSafety(train).safe() && doneWaiting()){ + phase = LaunchPhase.LAUNCHING_FROM_STANDSTILL; + train.getNextSection().setEntireBlockReservation(train); + goIntoSwitch = true; + playLaunchEffects(train); + } + break; + case LAUNCHING_FROM_STANDSTILL: + if(forwardsLaunch){ + newSpeed.approach(launchAcceleration, launchAcceleration, launchSpeed); + }else{ + newSpeed.approach(launchAcceleration, launchAcceleration, -launchSpeedBackward); + } + break; + case LAUNCHING: + newSpeed.approach(launchAcceleration, launchAcceleration, launchSpeed); + break; + } + } + + return calculateTrainMovement(train, section, newSpeed); + } + + private void playLaunchEffects(Train train){ + if(launchEffectTriggers == null) return; + launchEffectTriggers.forEach(e -> e.executeForTrain(train)); + } + + private void reset(){ + waitTicksState = 0; + phase = LaunchPhase.IDLE; + } + + private boolean doneWaiting(){ + if(waitTicksState >= waitTicks) + return true; + waitTicksState++; + return false; + } + + @Override + public void trainExitedAtStart(@Nullable Train train, @Nullable Section section) { + reset(); + } + + @Override + public void trainExitedAtEnd(@Nullable Train train, @Nullable Section section){ + reset(); + } + + @Override + public String getName() { + return "Launch"; + } + + @Override + public boolean canBlock() { + return true; + } + + @Override + public boolean canSpawnOn() { + return canSpawn; + } + + @Override + public Frame getSpawnFrame() { + return engageFrame; + } + + @Override + protected void setParentTrackOnFrames(Track parentTrack) { + engageFrame.setTrack(parentTrack); + } +} + +enum LaunchPhase{ + IDLE, + DRIVING, + STOPPING, + WAITING, + LAUNCHING_FROM_STANDSTILL, + LAUNCHING +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/ProximityUtils.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/ProximityUtils.java new file mode 100644 index 00000000..70c6bd4a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/ProximityUtils.java @@ -0,0 +1,26 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour; + +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +import java.util.List; + +public class ProximityUtils { + public static boolean isTooCloseToOtherTrains(Train train, List otherTrains, double minTrainDistance){ + boolean tooCloseToOther = false; + int trainFrameValue = train.getMiddleOfTrainFrame().getValue(); + + for(Train otherTrain : otherTrains){ + if(otherTrain == train) continue; + + int otherTrainFrameValue = otherTrain.getMiddleOfTrainFrame().getValue(); + if(otherTrainFrameValue < trainFrameValue) + break; // Do not care about trains behind us + + int distanceFrom = otherTrainFrameValue - trainFrameValue; + if(distanceFrom < minTrainDistance){ + tooCloseToOther = true; + } + } + return tooCloseToOther; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/TrackBehaviour.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/TrackBehaviour.java new file mode 100644 index 00000000..630548e7 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/TrackBehaviour.java @@ -0,0 +1,55 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.TrainMovement; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.Speed; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.Section; +import com.jverbruggen.jrides.models.ride.section.reference.SectionReference; + +import javax.annotation.Nullable; +import java.util.Collection; +import java.util.Map; + +public interface TrackBehaviour { + TrainMovement move(Speed currentSpeed, TrainHandle trainHandle, Section section); + void trainExitedAtStart(@Nullable Train train, @Nullable Section section); + void trainExitedAtEnd(@Nullable Train train, @Nullable Section section); + void trainPassed(Train train); + + String getName(); + boolean canBlock(); + boolean canSpawnOn(); + Frame getSpawnFrame(); + + void setParentTrack(Track parentTrack); + Track getParentTrack(); + + Section getSectionNext(Train train, boolean process); + Section getSectionPrevious(Train train, boolean process); + Section getSectionAtStart(Train train, boolean process); + Section getSectionAtEnd(Train train, boolean process); + boolean accepts(Train train); + + Collection
getAllNextSections(Train train); + Collection
getAllPreviousSections(Train train); + + boolean definesNextSection(); + Vector3 getBehaviourDefinedPosition(Vector3 originalPosition); + Quaternion getBehaviourDefinedOrientation(Quaternion originalOrientation); + + void populateSectionReferences(Map sectionMap); + + boolean definesNextAccepting(); + Section acceptAsNext(Train train, boolean canProcessPassed); + + boolean canHandleBlockSectionSafety(); + + boolean canHandleConnections(); + boolean previousConnectsToStart(); + boolean nextConnectsToStart(); +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/drive/BlockBrakeTrackBehaviour.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/drive/BlockBrakeTrackBehaviour.java new file mode 100644 index 00000000..dd01b120 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/drive/BlockBrakeTrackBehaviour.java @@ -0,0 +1,155 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour.drive; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.BaseTrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.CartMovementFactory; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.TrainMovement; +import com.jverbruggen.jrides.models.properties.Speed; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.Section; +import com.jverbruggen.jrides.models.ride.section.result.BlockSectionSafetyResult; + +import javax.annotation.Nullable; + +public class BlockBrakeTrackBehaviour extends BaseTrackBehaviour { + private final double deceleration; + private final double acceleration; + private final double driveSpeed; + + private BlockBrakePhase phase; + private final Frame stopFrame; + private final boolean canSpawn; + + private final int minWaitTicks; + private int minWaitTicksState; + + public BlockBrakeTrackBehaviour(CartMovementFactory cartMovementFactory, Frame stopFrame, boolean canSpawn, double driveSpeed, double deceleration, double acceleration, int minWaitTicks) { + super(cartMovementFactory); + this.deceleration = deceleration; + this.acceleration = acceleration; + this.driveSpeed = driveSpeed; + this.phase = BlockBrakePhase.IDLE; + this.stopFrame = stopFrame; + this.canSpawn = canSpawn; + + this.minWaitTicks = minWaitTicks; + this.minWaitTicksState = 0; + + trainExitedAtEnd(null, null); + } + + @Override + public TrainMovement move(Speed currentSpeed, TrainHandle trainHandle, Section section) { + Speed newSpeed = currentSpeed.clone(); + Train train = trainHandle.getTrain(); + + boolean goIntoSwitch = true; + while(goIntoSwitch){ + goIntoSwitch = false; + switch (phase){ + case IDLE: + train.setStatusMessage("Idle"); + if(getNextSectionSafety(train).safe() && minWaitTicks <= 0){ + phase = BlockBrakePhase.DRIVING; + train.getNextSection().setEntireBlockReservation(train); + } else + phase = BlockBrakePhase.DRIVING_UNTIL_STOP; + goIntoSwitch = true; + break; + case DRIVING_UNTIL_STOP: + train.setStatusMessage("Driving until stop"); + if(train.getHeadSection().hasPassed(stopFrame, train.getHeadOfTrainFrame())){ + if(getNextSectionSafety(train).safe() && minWaitTicks <= 0){ + phase = BlockBrakePhase.DRIVING; + train.getNextSection().setEntireBlockReservation(train); + }else{ + phase = BlockBrakePhase.STOPPING; + } + goIntoSwitch = true; + }else{ + newSpeed.approach(acceleration, deceleration, driveSpeed); + } + break; + case STOPPING: + train.setStatusMessage("Stopping" + newSpeed.getSpeedPerTick()); + if(newSpeed.isZero()){ + phase = BlockBrakePhase.WAITING; + goIntoSwitch = true; + } + newSpeed.minus(deceleration, 0); + break; + case WAITING: + BlockSectionSafetyResult safetyResult = getNextSectionSafety(train); + train.setStatusMessage("Waiting \n" + train.getHeadSection() + "\n" + + train.getHeadSection().next(train) + " safety: " + safetyResult); + if(safetyResult.safe() && isMinWaitTimerFinished()){ + train.getNextSection().setEntireBlockReservation(train); + resetMinWaitTimer(); + phase = BlockBrakePhase.DRIVING; + goIntoSwitch = true; + } + break; + case DRIVING: + train.setStatusMessage("Driving"); + newSpeed.approach(acceleration, deceleration, driveSpeed); + break; + } + } + + return calculateTrainMovement(train, section, newSpeed); + } + + private boolean isMinWaitTimerFinished(){ + if(minWaitTicks <= 0) return true; + return minWaitTicksState++ >= minWaitTicks; + } + + private void resetMinWaitTimer(){ + minWaitTicksState = 0; + } + + @Override + public void trainExitedAtStart(@Nullable Train train, @Nullable Section section) { + + } + + @Override + public void trainExitedAtEnd(@Nullable Train train, @Nullable Section section){ + this.phase = BlockBrakePhase.IDLE; + } + + @Override + public String getName() { + return "BlockBrake"; + } + + @Override + public boolean canBlock() { + return true; + } + + @Override + public boolean canSpawnOn() { + return canSpawn; + } + + @Override + public Frame getSpawnFrame() { + return stopFrame; + } + + @Override + protected void setParentTrackOnFrames(Track parentTrack) { + stopFrame.setTrack(parentTrack); + } +} + +enum BlockBrakePhase{ + IDLE, + DRIVING_UNTIL_STOP, + STOPPING, + WAITING, + DRIVING +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/drive/BrakeAndDriveTrackBehaviour.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/drive/BrakeAndDriveTrackBehaviour.java new file mode 100644 index 00000000..8d1e2838 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/drive/BrakeAndDriveTrackBehaviour.java @@ -0,0 +1,81 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour.drive; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.BaseTrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.CartMovementFactory; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.TrainMovement; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.Speed; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.Section; + +import javax.annotation.Nullable; + +public class BrakeAndDriveTrackBehaviour extends BaseTrackBehaviour { + private final boolean isIgnoreDirection; + private final double deceleration; + private final double acceleration; + private final double driveSpeed; + + public BrakeAndDriveTrackBehaviour(CartMovementFactory cartMovementFactory, boolean isIgnoreDirection, double driveSpeed, double deceleration, double acceleration) { + super(cartMovementFactory); + this.isIgnoreDirection = isIgnoreDirection; + this.deceleration = deceleration; + this.acceleration = acceleration; + this.driveSpeed = driveSpeed; + } + + @Override + public TrainMovement move(Speed currentSpeed, TrainHandle trainHandle, Section section) { + Speed newSpeed = currentSpeed.clone(); + Train train = trainHandle.getTrain(); + + if(isIgnoreDirection){ + if(newSpeed.isPositive()){ + newSpeed.approach(acceleration, deceleration, driveSpeed); + }else{ + newSpeed.approach(acceleration, deceleration, -driveSpeed); + } + }else{ + newSpeed.approach(acceleration, deceleration, driveSpeed); + } + + return calculateTrainMovement(train, section, newSpeed); + } + + @Override + public void trainExitedAtStart(@Nullable Train train, @Nullable Section section) { + + } + + @Override + public void trainExitedAtEnd(@Nullable Train train, @Nullable Section section){ + + } + + @Override + public String getName() { + return "BrakeAndDrive"; + } + + @Override + public boolean canBlock() { + return false; + } + + @Override + public boolean canSpawnOn() { + return false; + } + + @Override + public Frame getSpawnFrame() { + return null; + } + + @Override + protected void setParentTrackOnFrames(Track parentTrack) { + + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/drive/DriveAndReleaseTrackBehaviour.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/drive/DriveAndReleaseTrackBehaviour.java new file mode 100644 index 00000000..ca497525 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/drive/DriveAndReleaseTrackBehaviour.java @@ -0,0 +1,137 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour.drive; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.BaseTrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.FreeMovementTrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.CartMovementFactory; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.TrainMovement; +import com.jverbruggen.jrides.models.properties.Speed; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.Section; + +import javax.annotation.Nullable; + +enum DriveAndReleasePhase{ + IDLE, + DRIVING, + STOPPING, + WAITING, + RELEASE, +} + +public class DriveAndReleaseTrackBehaviour extends BaseTrackBehaviour { + private final double deceleration; + private final double acceleration; + private final double driveSpeed; + private DriveAndReleasePhase phase; + private final Frame stopFrame; + private final int minWaitTicks; + private int minWaitTicksState; + private final double gravityConstant; + private final double dragConstant; + + public DriveAndReleaseTrackBehaviour(CartMovementFactory cartMovementFactory, double driveSpeed, double deceleration, double acceleration, Frame stopFrame, int minWaitTicks, double gravityConstant, double dragConstant) { + super(cartMovementFactory); + this.deceleration = deceleration; + this.acceleration = acceleration; + this.driveSpeed = driveSpeed; + this.stopFrame = stopFrame; + this.minWaitTicks = minWaitTicks; + this.gravityConstant = gravityConstant; + this.dragConstant = dragConstant; + this.minWaitTicksState = 0; + this.phase = DriveAndReleasePhase.IDLE; + } + + @Override + public TrainMovement move(Speed currentSpeed, TrainHandle trainHandle, Section section) { + Speed newSpeed = currentSpeed.clone(); + Train train = trainHandle.getTrain(); + + boolean goIntoSwitch = true; + while(goIntoSwitch){ + goIntoSwitch = false; + switch (phase){ + case IDLE -> { + minWaitTicksState = 0; + phase = DriveAndReleasePhase.DRIVING; + goIntoSwitch = true; + } + case DRIVING -> { + if(shouldStop(train)){ + phase = DriveAndReleasePhase.STOPPING; + goIntoSwitch = true; + }else{ + newSpeed.approach(acceleration, deceleration, driveSpeed); + } + } + case STOPPING -> { + newSpeed.approach(acceleration, deceleration, 0); + if(newSpeed.isZero()){ + phase = DriveAndReleasePhase.WAITING; + goIntoSwitch = true; + } + } + case WAITING -> { + if(++minWaitTicksState >= minWaitTicks){ + phase = DriveAndReleasePhase.RELEASE; + goIntoSwitch = true; + } + } + case RELEASE -> newSpeed = FreeMovementTrackBehaviour.calculateGravityActedSpeed( + trainHandle, section, currentSpeed, gravityConstant, dragConstant + ); + } + } + + return calculateTrainMovement(train, section, newSpeed); + } + + private boolean shouldStop(Train train){ + if (driveSpeed >= 0) + return train.getHeadSection().hasPassed(stopFrame, train.getHeadOfTrainFrame()); + return train.getHeadSection().hasPassedInverse(stopFrame, train.getHeadOfTrainFrame()); + } + + private void trainExited(){ + this.phase = DriveAndReleasePhase.IDLE; + minWaitTicksState = 0; + } + + @Override + public void trainExitedAtStart(@Nullable Train train, @Nullable Section section) { + trainExited(); + } + + @Override + public void trainExitedAtEnd(@Nullable Train train, @Nullable Section section){ + trainExited(); + } + + @Override + public String getName() { + return "DriveAndRelease"; + } + + @Override + public boolean canBlock() { + return false; + } + + @Override + public boolean canSpawnOn() { + return false; + } + + @Override + public Frame getSpawnFrame() { + return null; + } + + @Override + protected void setParentTrackOnFrames(Track parentTrack) { + + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/drive/DriveStopDriveTrackBehaviour.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/drive/DriveStopDriveTrackBehaviour.java new file mode 100644 index 00000000..33ba43cf --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/drive/DriveStopDriveTrackBehaviour.java @@ -0,0 +1,134 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour.drive; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.BaseTrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.CartMovementFactory; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.TrainMovement; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.Speed; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.Section; + +import javax.annotation.Nullable; + + +enum DriveStopDrivePhase { + IDLE, + DRIVING_IN, + STOPPING, + WAITING, + DRIVING_OUT +} + +public class DriveStopDriveTrackBehaviour extends BaseTrackBehaviour { + private DriveStopDrivePhase phase; + private final int minWaitTicks; + private int minWaitTicksState; + + private final Frame stopFrame; + private final double deceleration; + private final double acceleration; + private final double driveSpeedIn; + private final double driveSpeedOut; + + public DriveStopDriveTrackBehaviour(CartMovementFactory cartMovementFactory, int minWaitTicks, Frame stopFrame, double deceleration, double acceleration, double driveSpeedIn, double driveSpeedOut) { + super(cartMovementFactory); + + this.minWaitTicks = minWaitTicks; + this.stopFrame = stopFrame; + this.deceleration = deceleration; + this.acceleration = acceleration; + this.driveSpeedIn = driveSpeedIn; + this.driveSpeedOut = driveSpeedOut; + trainExitedAtEnd(null, null); + } + + @Override + public TrainMovement move(Speed currentSpeed, TrainHandle trainHandle, Section section) { + Speed newSpeed = currentSpeed.clone(); + Train train = trainHandle.getTrain(); + + boolean goIntoSwitch = true; + while(goIntoSwitch){ + goIntoSwitch = false; + switch (phase){ + case IDLE -> { + minWaitTicksState = 0; + phase = DriveStopDrivePhase.DRIVING_IN; + goIntoSwitch = true; + } + case DRIVING_IN -> { + if(shouldStop(train)){ + phase = DriveStopDrivePhase.STOPPING; + goIntoSwitch = true; + }else{ + newSpeed.approach(acceleration, deceleration, driveSpeedIn); + } + } + case STOPPING -> { + newSpeed.approach(acceleration, deceleration, 0); + if(newSpeed.isZero()){ + phase = DriveStopDrivePhase.WAITING; + goIntoSwitch = true; + } + } + case WAITING -> { + if(++minWaitTicksState >= minWaitTicks){ + phase = DriveStopDrivePhase.DRIVING_OUT; + goIntoSwitch = true; + } + } + case DRIVING_OUT -> newSpeed.approach(acceleration, deceleration, driveSpeedOut); + } + } + + return calculateTrainMovement(train, section, newSpeed); + } + + private boolean shouldStop(Train train){ + if (driveSpeedIn >= 0) + return train.getHeadSection().hasPassed(stopFrame, train.getHeadOfTrainFrame()); + return train.getHeadSection().hasPassedInverse(stopFrame, train.getHeadOfTrainFrame()); + } + + @Override + public void trainExitedAtStart(@Nullable Train train, @Nullable Section section) { + trainExited(); + } + + @Override + public void trainExitedAtEnd(@Nullable Train train, @Nullable Section section) { + trainExited(); + } + + private void trainExited(){ + this.phase = DriveStopDrivePhase.IDLE; + this.minWaitTicksState = this.minWaitTicks; + } + + @Override + public String getName() { + return "DriveStopDrive"; + } + + @Override + public boolean canBlock() { + return false; + } + + @Override + public boolean canSpawnOn() { + return false; + } + + @Override + public Frame getSpawnFrame() { + return null; + } + + @Override + protected void setParentTrackOnFrames(Track parentTrack) { + + } +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/drive/ProximityDriveTrackBehaviour.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/drive/ProximityDriveTrackBehaviour.java new file mode 100644 index 00000000..488fb94f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/drive/ProximityDriveTrackBehaviour.java @@ -0,0 +1,218 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour.drive; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.BaseTrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.ProximityUtils; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.CartMovementFactory; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.TrainMovement; +import com.jverbruggen.jrides.models.properties.Speed; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.Section; +import com.jverbruggen.jrides.models.ride.section.SectionSafetyProvider; +import com.jverbruggen.jrides.models.ride.section.result.BlockSectionSafetyResult; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; + +public class ProximityDriveTrackBehaviour extends BaseTrackBehaviour implements SectionSafetyProvider { + private final boolean canSpawn; + private final double deceleration; + private final double acceleration; + private final double driveSpeed; + private final double minTrainDistance; + private final Frame stopFrame; + private final HashMap trainPhases; + private final List reservations; + + public ProximityDriveTrackBehaviour(CartMovementFactory cartMovementFactory, boolean canSpawn, double driveSpeed, double deceleration, double acceleration, double minTrainDistance, Frame stopFrame) { + super(cartMovementFactory); + this.canSpawn = canSpawn; + this.deceleration = deceleration; + this.acceleration = acceleration; + this.driveSpeed = driveSpeed; + this.minTrainDistance = minTrainDistance; + this.stopFrame = stopFrame; + this.trainPhases = new LinkedHashMap<>(); + this.reservations = new ArrayList<>(); + } + + @Override + public TrainMovement move(Speed currentSpeed, TrainHandle trainHandle, Section section) { + Speed newSpeed = currentSpeed.clone(); + Train train = trainHandle.getTrain(); + if(!trainPhases.containsKey(train)){ + throw new RuntimeException("New occupation not handled correctly"); + } + + boolean goIntoSwitch = true; + ProximityDrivePhase phase = trainPhases.get(train); + while(goIntoSwitch){ + goIntoSwitch = false; + + switch (phase) { + case DRIVING_UNTIL_STOP -> { + train.setStatusMessage("Driving until stop"); + if (train.getHeadSection().hasPassed(stopFrame, train.getHeadOfTrainFrame())) { + if (getNextSectionSafety(train).safe()) { + phase = ProximityDrivePhase.DRIVING_TO_NEXT; + train.getNextSection().setEntireBlockReservation(train); + } else { + phase = ProximityDrivePhase.STOPPING; + } + goIntoSwitch = true; + } else { + boolean tooCloseToOther = this.isTooCloseToOtherTrains(train); + + if(tooCloseToOther){ + newSpeed.approach(acceleration, deceleration, 0); + }else{ + newSpeed.approach(acceleration, deceleration, driveSpeed); + } + } + } + case STOPPING -> { + train.setStatusMessage("Stopping" + newSpeed.getSpeedPerTick()); + if (newSpeed.isZero()) { + phase = ProximityDrivePhase.WAITING; + goIntoSwitch = true; + } + newSpeed.minus(deceleration, 0); + } + case WAITING -> { + train.setStatusMessage("Waiting \n" + train.getHeadSection() + "\n" + + train.getHeadSection().next(train)); + if (getNextSectionSafety(train).safe()) { + train.getNextSection().setEntireBlockReservation(train); + phase = ProximityDrivePhase.DRIVING_TO_NEXT; + goIntoSwitch = true; + } + } + case DRIVING_TO_NEXT -> { + train.setStatusMessage("Driving"); + newSpeed.approach(acceleration, deceleration, driveSpeed); + } + } + } + + + return calculateTrainMovement(train, section, newSpeed); + } + + private boolean isTooCloseToOtherTrains(Train train){ + return ProximityUtils.isTooCloseToOtherTrains(train, trainPhases.keySet().stream().toList(), minTrainDistance); + } + + @Override + public void trainExitedAtStart(@Nullable Train train, @Nullable Section section) { + trainExited(train); + } + + @Override + public void trainExitedAtEnd(@Nullable Train train, @Nullable Section section){ + trainExited(train); + } + + private void trainExited(@Nullable Train train){ + if(train == null) return; + trainPhases.remove(train); + reservations.remove(train); + } + + @Override + public String getName() { + return "ProximityDrive"; + } + + @Override + public boolean canBlock() { + return true; + } + + @Override + public boolean canSpawnOn() { + return canSpawn; + } + + @Override + public Frame getSpawnFrame() { + return stopFrame; + } + + @Override + protected void setParentTrackOnFrames(Track parentTrack) { + stopFrame.setTrack(parentTrack); + } + + @Override + public boolean canHandleBlockSectionSafety() { + return true; + } + + @Override + public BlockSectionSafetyResult getEnteringSafety(Train train, Section nextSection) { +// BlockSectionSafetyResult nextSectionSafety = nextSection.getBlockSectionSafety(train); +// if() + return new BlockSectionSafetyResult(true, train, ""); + } + + @Override + public boolean canHandleOccupation(@Nonnull Train train) { + if(reservations.contains(train)) return true; + if(trainPhases.containsKey(train)) return true; + + return !ProximityUtils.isTooCloseToOtherTrains(train, trainPhases.keySet().stream().toList(), minTrainDistance); + } + + @Override + public void handleNewReservation(@Nonnull Train train) { + reservations.add(train); + } + + @Override + public void handleClearReservation(@Nonnull Train train) { + reservations.remove(train); + } + + @Override + public Train getReservation() { + return null; + } + + @Override + public void handleNewOccupation(@Nonnull Train train) { + trainPhases.put(train, ProximityDrivePhase.DRIVING_UNTIL_STOP); + } + + @Override + public void handleClearOccupation(@Nonnull Train train) { + + } + + @Override + public boolean isReservedBy(@Nonnull Train train) { + return isOccupiedBy(train); + } + + @Override + public boolean isOccupied() { + return !trainPhases.isEmpty(); + } + + @Override + public boolean isOccupiedBy(@Nonnull Train train) { + return trainPhases.containsKey(train); + } +} + +enum ProximityDrivePhase{ + DRIVING_UNTIL_STOP, + STOPPING, + WAITING, + DRIVING_TO_NEXT +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/drive/TrimBrakeTrackBehaviour.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/drive/TrimBrakeTrackBehaviour.java new file mode 100644 index 00000000..8ee0c5fa --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/drive/TrimBrakeTrackBehaviour.java @@ -0,0 +1,71 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour.drive; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.BaseTrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.FreeMovementTrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.CartMovementFactory; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.TrainMovement; +import com.jverbruggen.jrides.models.properties.Speed; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.Section; + +import javax.annotation.Nullable; + +public class TrimBrakeTrackBehaviour extends BaseTrackBehaviour { + private final double gravityConstant; + private final double dragConstantWithTrim; + + public TrimBrakeTrackBehaviour(CartMovementFactory cartMovementFactory, double gravityConstant, double dragConstantWithTrim) { + super(cartMovementFactory); + this.gravityConstant = gravityConstant; + this.dragConstantWithTrim = dragConstantWithTrim; + } + + @Override + public TrainMovement move(Speed currentSpeed, TrainHandle trainHandle, Section section) { + Train train = trainHandle.getTrain(); + + Speed newSpeed = FreeMovementTrackBehaviour.calculateGravityActedSpeed( + trainHandle, section, currentSpeed, gravityConstant, dragConstantWithTrim + ); + + return calculateTrainMovement(train, section, newSpeed); + } + + @Override + public void trainExitedAtStart(@Nullable Train train, @Nullable Section section) { + + } + + @Override + public void trainExitedAtEnd(@Nullable Train train, @Nullable Section section){ + + } + + @Override + public String getName() { + return "TrimBrake"; + } + + @Override + public boolean canBlock() { + return false; + } + + @Override + public boolean canSpawnOn() { + return false; + } + + @Override + public Frame getSpawnFrame() { + return null; + } + + @Override + protected void setParentTrackOnFrames(Track parentTrack) { + + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/factory/TrackBehaviourFactory.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/factory/TrackBehaviourFactory.java new file mode 100644 index 00000000..ea89b2b4 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/factory/TrackBehaviourFactory.java @@ -0,0 +1,306 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour.factory; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.FreeMovementTrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.LaunchTrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.station.StationTrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.TrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.drive.*; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.CartMovementFactory; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.transfer.TrainDisplacerTransferTrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.point.SwitchBehaviour; +import com.jverbruggen.jrides.config.coaster.CoasterConfig; +import com.jverbruggen.jrides.config.coaster.objects.section.base.PointSectionConfig; +import com.jverbruggen.jrides.config.coaster.objects.section.base.RangedSectionConfig; +import com.jverbruggen.jrides.config.coaster.objects.section.point.SwitchSectionSpecConfig; +import com.jverbruggen.jrides.config.coaster.objects.section.ranged.*; +import com.jverbruggen.jrides.config.coaster.objects.section.ranged.transfer.TransferSectionPositionSpecConfig; +import com.jverbruggen.jrides.config.coaster.objects.section.ranged.transfer.TransferSectionSpecConfig; +import com.jverbruggen.jrides.config.gates.GateOwnerConfigSpec; +import com.jverbruggen.jrides.control.DispatchLock; +import com.jverbruggen.jrides.control.DispatchLockCollection; +import com.jverbruggen.jrides.control.SimpleDispatchLock; +import com.jverbruggen.jrides.control.trigger.*; +import com.jverbruggen.jrides.effect.EffectTriggerFactory; +import com.jverbruggen.jrides.effect.handle.train.TrainEffectTriggerHandle; +import com.jverbruggen.jrides.items.ItemStackFactory; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.entity.TrainModelItem; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.frame.FrameRange; +import com.jverbruggen.jrides.models.properties.frame.SimpleFrame; +import com.jverbruggen.jrides.models.ride.CoasterStationHandle; +import com.jverbruggen.jrides.models.ride.RideType; +import com.jverbruggen.jrides.models.ride.coaster.trackswitch.SwitchPosition; +import com.jverbruggen.jrides.models.ride.coaster.transfer.Transfer; +import com.jverbruggen.jrides.models.ride.coaster.transfer.TransferPosition; +import com.jverbruggen.jrides.models.ride.gate.Gate; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.viewport.ViewportManager; +import org.bukkit.Material; +import org.bukkit.World; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class TrackBehaviourFactory { + private final CartMovementFactory cartMovementFactory; + private final EffectTriggerFactory effectTriggerFactory; + private final LanguageFile languageFile; + private final ViewportManager viewportManager; + + public TrackBehaviourFactory() { + this.cartMovementFactory = ServiceProvider.getSingleton(CartMovementFactory.class); + this.effectTriggerFactory = ServiceProvider.getSingleton(EffectTriggerFactory.class); + this.languageFile = ServiceProvider.getSingleton(LanguageFile.class); + this.viewportManager = ServiceProvider.getSingleton(ViewportManager.class); + } + + public TrackBehaviour getTrackBehaviour(double gravityConstant, double dragConstant){ + return new FreeMovementTrackBehaviour(cartMovementFactory, gravityConstant, dragConstant); + } + + public TrackBehaviour getBlockBrakeBehaviour(RangedSectionConfig rangedSectionConfig, int totalFrames){ + BlockSectionSpecConfig blockSectionSpecConfig = rangedSectionConfig.getBlockSectionSpec(); + double engagePercentage = blockSectionSpecConfig.getEngage(); + Frame lowerRange = new SimpleFrame(rangedSectionConfig.getLowerRange()); + Frame upperRange = new SimpleFrame(rangedSectionConfig.getUpperRange()); + boolean canSpawn = blockSectionSpecConfig.canSpawn(); + double driveSpeed = blockSectionSpecConfig.getDriveSpeed(); + double acceleration = blockSectionSpecConfig.getAcceleration(); + double deceleration = blockSectionSpecConfig.getDeceleration(); + int minWaitTicks = blockSectionSpecConfig.getMinWaitTicks(); + + Frame blockBrakeEngageFrame = new FrameRange(lowerRange, upperRange, totalFrames).getInBetween(engagePercentage); + + return new BlockBrakeTrackBehaviour(cartMovementFactory, blockBrakeEngageFrame, canSpawn, driveSpeed, deceleration, acceleration, minWaitTicks); + } + + public TrackBehaviour getLaunchBehaviour(CoasterHandle coasterHandle, Frame engageFrame, boolean canSpawn, double driveSpeed, double acceleration, double deceleration, boolean isForwardsLaunch, int waitTicks, double launchAcceleration, double launchSpeed, double launchSpeedBackward, List launchEffectStrings){ + String rideIdentifier = coasterHandle.getRide().getIdentifier(); + List launchEffectTriggers = effectTriggerFactory.getFramelessEffectTriggers(RideType.COASTER, rideIdentifier, launchEffectStrings); + + return new LaunchTrackBehaviour(cartMovementFactory, canSpawn, driveSpeed, deceleration, acceleration, isForwardsLaunch, waitTicks, engageFrame, launchAcceleration, launchSpeed, launchSpeedBackward, launchEffectTriggers); + } + + public TrackBehaviour getStationBehaviour(Frame blockBrakeEngageFrame, CoasterHandle coasterHandle, RangedSectionConfig rangedSectionConfig, GateOwnerConfigSpec gateSpec){ + String rideIdentifier = coasterHandle.getRide().getIdentifier(); + String shortStationName = rangedSectionConfig.getIdentifier(); + String stationName = rideIdentifier + "_station_" + shortStationName; + World world = JRidesPlugin.getWorld(); + + DispatchLockCollection dispatchLockCollection = new DispatchLockCollection("Main locks"); + + DispatchLock trainInStationDispatchLock = new SimpleDispatchLock(dispatchLockCollection, + languageFile.get(LanguageFileField.NOTIFICATION_RIDE_NO_TRAIN_PRESENT), true); + DispatchLock blockSectionOccupiedDispatchLock = new SimpleDispatchLock(dispatchLockCollection, + languageFile.get(LanguageFileField.NOTIFICATION_RIDE_NEXT_BLOCK_OCCUPIED), true); + DispatchLock minimumWaitTimeDispatchLock = new SimpleDispatchLock(dispatchLockCollection, + languageFile.get(LanguageFileField.NOTIFICATION_RIDE_WAITING_TIME), true); + DispatchLock restraintLock = new SimpleDispatchLock(dispatchLockCollection, + languageFile.get(LanguageFileField.NOTIFICATION_RIDE_RESTRAINTS_NOT_CLOSED), true); + DispatchLockCollection gatesGenericLock = new DispatchLockCollection( + languageFile.get(LanguageFileField.NOTIFICATION_RIDE_GATES_NOT_CLOSED), dispatchLockCollection); + + List gates = gateSpec != null + ? gateSpec.createGates(stationName, world, gatesGenericLock) + : new ArrayList<>(); + + TriggerContext triggerContext = new TriggerContext( + dispatchLockCollection, + trainInStationDispatchLock, + new SimpleDispatchTrigger(dispatchLockCollection), + new GateTrigger(gatesGenericLock), + new RestraintTrigger(restraintLock)); + + CoasterStationConfig coasterStationConfig = rangedSectionConfig.getStationSectionSpec(); + double driveSpeed = coasterStationConfig.getDriveSpeed(); + + CoasterStationHandle stationHandle = coasterStationConfig.createStationHandle( + stationName, shortStationName, triggerContext, coasterHandle, + gates, minimumWaitTimeDispatchLock); + + return new StationTrackBehaviour(coasterHandle, cartMovementFactory, blockBrakeEngageFrame, coasterStationConfig.canSpawn(), triggerContext, + stationHandle, trainInStationDispatchLock, blockSectionOccupiedDispatchLock, restraintLock, driveSpeed, + coasterStationConfig.isForwardsDispatch(), coasterStationConfig.getPassThroughCount()); + } + + private TrackBehaviour getSwitchBehaviour(SwitchSectionSpecConfig switchSectionSpecConfig) { + List destinations = switchSectionSpecConfig.getDestinations() + .stream() + .map(SwitchPosition::new) + .collect(Collectors.toList()); + SwitchPosition origin = new SwitchPosition(switchSectionSpecConfig.getOrigin()); + + return new SwitchBehaviour(cartMovementFactory, destinations, origin); + } + + public TrackBehaviour getTrackBehaviourFor(CoasterHandle coasterHandle, CoasterConfig coasterConfig, RangedSectionConfig rangedSectionConfig, int totalFrames){ + String type = rangedSectionConfig.getType(); + String identifier = rangedSectionConfig.getIdentifier(); + + if(type.equalsIgnoreCase("track")){ + double gravityConstant = coasterConfig.getGravityConstant(); + double dragConstant = coasterConfig.getDragConstant(); + return getTrackBehaviour(gravityConstant, dragConstant); + }else if(type.equalsIgnoreCase("blocksection")){ + return getBlockBrakeBehaviour(rangedSectionConfig, totalFrames); + }else if(type.equalsIgnoreCase("station")){ + CoasterStationConfig stationSectionSpecConfig = rangedSectionConfig.getStationSectionSpec(); + GateOwnerConfigSpec gateSpec = coasterConfig.getGates().getGateOwnerSpec(identifier).orElse(null); + + double engagePercentage = stationSectionSpecConfig.getEngage(); + Frame lowerRange = new SimpleFrame(rangedSectionConfig.getLowerRange()); + Frame upperRange = new SimpleFrame(rangedSectionConfig.getUpperRange()); + + Frame blockBrakeEngageFrame = new FrameRange(lowerRange, upperRange, totalFrames).getInBetween(engagePercentage); + return getStationBehaviour(blockBrakeEngageFrame, coasterHandle, rangedSectionConfig, gateSpec); + }else if(type.equalsIgnoreCase("brake")){ + BrakeSectionSpecConfig brakeSectionSpecConfig = rangedSectionConfig.getBrakeSectionSpec(); + double driveSpeed = brakeSectionSpecConfig.getDriveSpeed(); + double deceleration = brakeSectionSpecConfig.getDeceleration(); + return new BrakeAndDriveTrackBehaviour(cartMovementFactory, false, driveSpeed, deceleration, deceleration); + }else if(type.equalsIgnoreCase("trim")){ + TrimBrakeSectionSpecConfig trimBrakeSectionSpecConfig = rangedSectionConfig.getTrimBrakeSectionSpecConfig(); + double dragConstantWithTrim = trimBrakeSectionSpecConfig.getTrimResistanceConstant() * coasterConfig.getDragConstant(); + return new TrimBrakeTrackBehaviour(cartMovementFactory, coasterConfig.getGravityConstant(), dragConstantWithTrim); + }else if(type.equalsIgnoreCase("drive")){ + DriveSectionSpecConfig driveSectionSpecConfig = rangedSectionConfig.getDriveSectionSpec(); + boolean ignoreDirection = driveSectionSpecConfig.isIgnoreDirection(); + double driveSpeed = driveSectionSpecConfig.getDriveSpeed(); + double acceleration = driveSectionSpecConfig.getAcceleration(); + double deceleration = driveSectionSpecConfig.getDeceleration(); + return new BrakeAndDriveTrackBehaviour(cartMovementFactory, ignoreDirection, driveSpeed, deceleration, acceleration); + }else if(type.equalsIgnoreCase("proximityDrive")){ + ProximityDriveSectionSpecConfig driveSectionSpecConfig = rangedSectionConfig.getProximityDriveSectionSpec(); + boolean canSpawn = driveSectionSpecConfig.canSpawn(); + double driveSpeed = driveSectionSpecConfig.getDriveSpeed(); + double acceleration = driveSectionSpecConfig.getAcceleration(); + double deceleration = driveSectionSpecConfig.getDeceleration(); + int minTrainDistance = driveSectionSpecConfig.getMinTrainDistance(); + + Frame lowerRange = new SimpleFrame(rangedSectionConfig.getLowerRange()); + Frame upperRange = new SimpleFrame(rangedSectionConfig.getUpperRange()); + Frame stopFrame = Frame.getDistanceFromUpperFrame(lowerRange, upperRange, 10); + + return new ProximityDriveTrackBehaviour(cartMovementFactory, canSpawn, driveSpeed, deceleration, acceleration, minTrainDistance, stopFrame); + }else if(type.equalsIgnoreCase("driveAndRelease")){ + DriveAndReleaseSectionSpecConfig driveAndReleaseSectionSpecConfig = rangedSectionConfig.getDriveAndReleaseSectionSpecConfig(); + double driveSpeed = driveAndReleaseSectionSpecConfig.getDriveSpeed(); + double acceleration = driveAndReleaseSectionSpecConfig.getAcceleration(); + double deceleration = driveAndReleaseSectionSpecConfig.getDeceleration(); + + double engagePercentage = driveAndReleaseSectionSpecConfig.getEngage(); + Frame lowerRange = new SimpleFrame(rangedSectionConfig.getLowerRange()); + Frame upperRange = new SimpleFrame(rangedSectionConfig.getUpperRange()); + + Frame stopFrame = new FrameRange(lowerRange, upperRange, totalFrames).getInBetween(engagePercentage); + + int minWaitTicks = driveAndReleaseSectionSpecConfig.getWaitTicks(); + + return new DriveAndReleaseTrackBehaviour(cartMovementFactory, driveSpeed, deceleration, acceleration, + stopFrame, minWaitTicks, coasterConfig.getGravityConstant(), coasterConfig.getDragConstant()); + }else if(type.equalsIgnoreCase("driveStopDrive")){ + DriveStopDriveSectionSpecConfig driveStopDriveSectionSpecConfig = rangedSectionConfig.getDriveStopDriveSectionSpecConfig(); + double driveSpeedIn = driveStopDriveSectionSpecConfig.getDriveSpeedIn(); + double driveSpeedOut = driveStopDriveSectionSpecConfig.getDriveSpeedOut(); + double acceleration = driveStopDriveSectionSpecConfig.getAcceleration(); + double deceleration = driveStopDriveSectionSpecConfig.getDeceleration(); + + double engagePercentage = driveStopDriveSectionSpecConfig.getEngage(); + Frame lowerRange = new SimpleFrame(rangedSectionConfig.getLowerRange()); + Frame upperRange = new SimpleFrame(rangedSectionConfig.getUpperRange()); + + Frame stopFrame = new FrameRange(lowerRange, upperRange, totalFrames).getInBetween(engagePercentage); + + int minWaitTicks = driveStopDriveSectionSpecConfig.getWaitTicks(); + + return new DriveStopDriveTrackBehaviour(cartMovementFactory, minWaitTicks, stopFrame, deceleration, acceleration, + driveSpeedIn, driveSpeedOut); + }else if(type.equalsIgnoreCase("launch")){ + LaunchSectionSpecConfig launchSectionSpecConfig = rangedSectionConfig.getLaunchSectionSpecConfig(); + double engagePercentage = launchSectionSpecConfig.getEngage(); + Frame lowerRange = new SimpleFrame(rangedSectionConfig.getLowerRange()); + Frame upperRange = new SimpleFrame(rangedSectionConfig.getUpperRange()); + Frame engageFrame = new FrameRange(lowerRange, upperRange, totalFrames).getInBetween(engagePercentage); + + boolean canSpawn = launchSectionSpecConfig.canSpawn(); + double driveSpeed = launchSectionSpecConfig.getDriveSpeed(); + double acceleration = launchSectionSpecConfig.getAcceleration(); + double deceleration = launchSectionSpecConfig.getDeceleration(); + boolean isForwardsLaunch = launchSectionSpecConfig.isForwardsLaunch(); + int waitTicks = launchSectionSpecConfig.getWaitTicks(); + double launchAcceleration = launchSectionSpecConfig.getLaunchAcceleration(); + double launchSpeed = launchSectionSpecConfig.getLaunchSpeed(); + double launchSpeedBackward = launchSectionSpecConfig.getLaunchSpeedBackward(); + List launchEffectsString = launchSectionSpecConfig.getLaunchEffectsConfig().getLaunchEffects(); + + return getLaunchBehaviour(coasterHandle, engageFrame, canSpawn, driveSpeed, acceleration, deceleration, isForwardsLaunch, waitTicks, launchAcceleration, launchSpeed, launchSpeedBackward, launchEffectsString); + }else if(type.equalsIgnoreCase("transfer")){ + TransferSectionSpecConfig transferSectionSpecConfig = rangedSectionConfig.getTransferSectionSpec(); + + Vector3 origin = transferSectionSpecConfig.getOrigin(); + double engagePercentage = transferSectionSpecConfig.getEngage(); + Frame lowerRange = new SimpleFrame(rangedSectionConfig.getLowerRange()); + Frame upperRange = new SimpleFrame(rangedSectionConfig.getUpperRange()); + Frame engageFrame = new FrameRange(lowerRange, upperRange, totalFrames).getInBetween(engagePercentage); + Vector3 modelOffsetPosition = transferSectionSpecConfig.getModelOffsetPosition(); + Vector3 modelOffsetRotation = transferSectionSpecConfig.getModelOffsetRotation(); + double enterDriveSpeed = transferSectionSpecConfig.getEnterDriveSpeed(); + double exitDriveSpeed = transferSectionSpecConfig.getExitDriveSpeed(); + double acceleration = transferSectionSpecConfig.getAcceleration(); + double deceleration = transferSectionSpecConfig.getDeceleration(); + + List transferPositions = new ArrayList<>(); + for(TransferSectionPositionSpecConfig transferSectionPositionSpecConfig : transferSectionSpecConfig.getPositions()){ + String sectionAtStartReference = transferSectionPositionSpecConfig.getSectionAtStart(); + String sectionAtEndReference = transferSectionPositionSpecConfig.getSectionAtEnd(); + boolean sectionAtStartForwards = transferSectionPositionSpecConfig.isSectionAtStartForwards(); + boolean sectionAtEndForwards = transferSectionPositionSpecConfig.isSectionAtEndForwards(); + boolean sectionAtStartConnectsToStart = transferSectionPositionSpecConfig.isSectionAtStartConnectsToStart(); + boolean sectionAtEndConnectsToStart = transferSectionPositionSpecConfig.isSectionAtEndConnectsToStart(); + Vector3 position = Vector3.add(origin, transferSectionPositionSpecConfig.getPosition()); + Vector3 rotation = transferSectionPositionSpecConfig.getRotation(); + int moveTicks = transferSectionPositionSpecConfig.getMoveTicks(); + + Quaternion orientation = Quaternion.fromAnglesVector(rotation); + transferPositions.add(new TransferPosition(position, orientation, moveTicks, sectionAtStartReference, sectionAtEndReference, sectionAtStartForwards, sectionAtEndForwards, sectionAtStartConnectsToStart, sectionAtEndConnectsToStart)); + } + + TransferPosition originTransferPosition = transferPositions.get(0); + + Quaternion modelOffsetOrientation = originTransferPosition.getOrientation().clone(); + modelOffsetOrientation.rotateYawPitchRoll(modelOffsetRotation); + + VirtualEntity virtualEntity = viewportManager.spawnModelEntity( + Vector3.add(originTransferPosition.getLocation(), modelOffsetPosition), + new TrainModelItem(ItemStackFactory.getCoasterStack(Material.DIAMOND_HOE, 2, true))); + virtualEntity.setRotation(modelOffsetOrientation); + + Transfer transfer = new Transfer(transferPositions, virtualEntity, origin, modelOffsetPosition, modelOffsetRotation); + coasterHandle.addTransfer(transfer); + coasterHandle.addUnlockable(identifier, transfer); + + return new TrainDisplacerTransferTrackBehaviour(cartMovementFactory, enterDriveSpeed, deceleration, acceleration, exitDriveSpeed, engageFrame, transfer); + } + + JRidesPlugin.getLogger().severe("Unknown section type " + type); + return null; + } + + public TrackBehaviour getTrackBehaviourFor(CoasterHandle coasterHandle, CoasterConfig coasterConfig, PointSectionConfig pointSectionConfig) { + String type = pointSectionConfig.getType(); + + if(type.equalsIgnoreCase("switch")){ + return getSwitchBehaviour(pointSectionConfig.getSwitchSectionSpecConfig()); + } + + throw new RuntimeException("Unknown point section type " + type); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/point/SwitchBehaviour.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/point/SwitchBehaviour.java new file mode 100644 index 00000000..130aeb82 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/point/SwitchBehaviour.java @@ -0,0 +1,169 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour.point; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.BaseTrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.CartMovementFactory; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.TrainMovement; +import com.jverbruggen.jrides.logging.LogType; +import com.jverbruggen.jrides.models.properties.Speed; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.trackswitch.SwitchPosition; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.Section; +import com.jverbruggen.jrides.models.ride.section.reference.SectionReference; + +import javax.annotation.Nullable; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class SwitchBehaviour extends BaseTrackBehaviour { + private List destinations; + private SwitchPosition origin; + + private Section selectedDestination; + + private int roundRobinState; + private @Nullable Train lastTrain; + + public SwitchBehaviour(CartMovementFactory cartMovementFactory, List destinations, SwitchPosition origin) { + super(cartMovementFactory); + this.destinations = destinations; + this.origin = origin; + this.roundRobinState = 0; + this.lastTrain = null; + } + + private void updateRoundRobinState(){ + if(++this.roundRobinState >= destinations.size()) + this.roundRobinState = 0; + } + + private void selectNewDestination(@Nullable Train train){ + if(destinations.size() == 0) + throw new RuntimeException("Switch does not lead anywhere!"); + + SwitchPosition nextPosition = destinations.get(this.roundRobinState); + if(!nextPosition.availableFor(train)){ + nextPosition = destinations.stream() + .filter(p -> p.availableFor(train)) + .findFirst() + .orElse(nextPosition); + } + + selectedDestination = nextPosition.getDestination(); + + JRidesPlugin.getLogger().info(LogType.SECTIONS, "Next destination for switch: " + selectedDestination); + updateRoundRobinState(); + } + + @Override + protected void setParentTrackOnFrames(Track parentTrack) { + + } + + @Override + public TrainMovement move(Speed currentSpeed, TrainHandle trainHandle, Section section) { + throw new RuntimeException("Should not move in point"); + } + + @Override + public boolean definesNextAccepting() { + return true; + } + + @Override + public Section acceptAsNext(Train train, boolean canProcessPassed) { + if(canProcessPassed) trainPassed(train); + + return getSectionAtEnd(train, canProcessPassed); + } + + @Override + public void trainExitedAtStart(@Nullable Train train, @Nullable Section section) { + } + + @Override + public void trainExitedAtEnd(@Nullable Train train, @Nullable Section section) { + } + + @Override + public void trainPassed(Train train) { +// selectNewDestination(); + if(lastTrain == train) + lastTrain = null; + } + + @Override + public String getName() { + return null; + } + + @Override + public boolean canBlock() { + return false; + } + + @Override + public boolean canSpawnOn() { + return false; + } + + @Override + public Frame getSpawnFrame() { + return null; + } + + @Override + public boolean definesNextSection() { + return true; + } + + @Override + public Section getSectionAtStart(Train train, boolean process) { + if(process && lastTrain != train && train != null){ + lastTrain = train; + newTrainEntered(train); + } + return origin.getDestination(); + } + + @Override + public Section getSectionAtEnd(Train train, boolean process) { + if(train != null){ + if(process && lastTrain != train){ + lastTrain = train; + newTrainEntered(train); + } + + List
matchingInReservation = train.getReservedSections().stream() + .filter(s -> destinations.stream() + .anyMatch(d -> d.getDestination().equals(s))) + .collect(Collectors.toList()); + + if(matchingInReservation.size() > 0){ + JRidesPlugin.getLogger().info(LogType.SECTIONS, "Matches in reservation: " + matchingInReservation.get(0)); + return matchingInReservation.get(0); + } + } + + return selectedDestination; + } + + @Override + public void populateSectionReferences(Map sectionMap) { + for(SwitchPosition destination : destinations){ + destination.populateWith(sectionMap); + } + + origin.populateWith(sectionMap); + + this.selectNewDestination(null); + } + + private void newTrainEntered(Train train){ + selectNewDestination(train); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/result/CartMovement.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/result/CartMovement.java new file mode 100644 index 00000000..ba2b8bab --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/result/CartMovement.java @@ -0,0 +1,22 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour.result; + +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; + +public final class CartMovement { + private final Vector3 location; + private final Quaternion orientation; + + public CartMovement(Vector3 location, Quaternion orientation) { + this.location = location; + this.orientation = orientation; + } + + public Vector3 getLocation() { + return location; + } + + public Quaternion getOrientation() { + return orientation; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/result/CartMovementFactory.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/result/CartMovementFactory.java new file mode 100644 index 00000000..26a67cab --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/result/CartMovementFactory.java @@ -0,0 +1,45 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour.result; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.math.VectorQuaternionState; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.train.CoasterCart; +import com.jverbruggen.jrides.models.ride.section.Section; +import com.jverbruggen.jrides.models.ride.section.provider.SectionProvider; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; + +import java.util.HashMap; +import java.util.List; + +public class CartMovementFactory { + private final SectionProvider sectionProvider; + + public CartMovementFactory() { + this.sectionProvider = ServiceProvider.getSingleton(SectionProvider.class); + } + + public HashMap createOnTrackCartMovement(TrainHandle trainHandle, List carts, int speedFrameIncrement, Section section){ + HashMap cartMovements = new HashMap<>(); + + for(CoasterCart cart : carts){ + Frame cartFrame = cart.getFrame(); + Frame newShadedCartFrame = cartFrame.clone().add(speedFrameIncrement); + + sectionProvider.addFramesWithSectionLogic(trainHandle, cartFrame, newShadedCartFrame.getValue()); + + Section cartSection = cartFrame.getSection(); + Vector3 cartPositionOnTrack = cartSection.getLocationFor(cartFrame); + Quaternion orientation = cartSection.getOrientationFor(cartFrame).clone(); + if(cartFrame.isInvertedFrameAddition()) + orientation.rotateY(180); + + VectorQuaternionState vectorQuaternionState = CoasterCart.calculateLocation(cartPositionOnTrack, cart.getTrackOffset(), orientation, cart.getRotationOffset()); + + cartMovements.put(cart, new CartMovement(vectorQuaternionState.getVector(), vectorQuaternionState.getQuaternion())); + } + + return cartMovements; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/result/TrainMovement.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/result/TrainMovement.java new file mode 100644 index 00000000..3d20a549 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/result/TrainMovement.java @@ -0,0 +1,54 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour.result; + +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.Speed; +import com.jverbruggen.jrides.models.ride.coaster.train.CoasterCart; + +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public final class TrainMovement { + private final Speed newSpeed; + private final Frame newHeadOfTrainFrame; + private final Frame newMiddleOfTrainFrame; + private final Frame newTailOfTrainFrame; + private final Vector3 newTrainLocation; + private final HashMap cartMovements; + + public TrainMovement(Speed newSpeed, Frame newHeadOfTrainFrame, Frame newMiddleOfTrainFrame, Frame newTailOfTrainFrame, Vector3 newTrainLocation, HashMap cartMovements) { + this.newSpeed = newSpeed; + this.newHeadOfTrainFrame = newHeadOfTrainFrame; + this.newMiddleOfTrainFrame = newMiddleOfTrainFrame; + this.newTailOfTrainFrame = newTailOfTrainFrame; + this.newTrainLocation = newTrainLocation; + this.cartMovements = cartMovements; + } + + public Speed getNewSpeed() { + return newSpeed; + } + + public Frame getNewHeadOfTrainFrame() { + return newHeadOfTrainFrame; + } + + public Frame getNewMiddleOfTrainFrame() { + return newMiddleOfTrainFrame; + } + + public Frame getNewTailOfTrainFrame() { + return newTailOfTrainFrame; + } + + public Vector3 getNewTrainLocation() { + return newTrainLocation; + } + + public @Nullable Set> getCartMovements() { + if(cartMovements == null) return null; + return cartMovements.entrySet(); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/station/StationPhase.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/station/StationPhase.java new file mode 100644 index 00000000..61b6ade6 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/station/StationPhase.java @@ -0,0 +1,43 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour.station; + +public enum StationPhase{ + /** + * Waiting for a train to arrive. + */ + IDLE, + + /** + * Used when a train is entering the station backwards. + */ + REVERSING, + + /** + * Train drives towards the stopping point. + */ + ARRIVING, + + /** + * Decelerating action towards stopping point. + */ + STOPPING, + + /** + * Stationary. Train is in a safe and still position. + */ + STATIONARY, + + /** + * Dispatch action was given, but still waiting for it to be safe. + */ + WAITING, + + /** + * Departing from station. + */ + DEPARTING, + + /** + * Passing through skips the station behaviour and just lets the train pass with default physics. + */ + PASSING_THROUGH +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/station/StationTrackBehaviour.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/station/StationTrackBehaviour.java new file mode 100644 index 00000000..fa15302a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/station/StationTrackBehaviour.java @@ -0,0 +1,263 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour.station; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.BaseTrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.FreeMovementTrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.CartMovementFactory; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.TrainMovement; +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.control.DispatchLock; +import com.jverbruggen.jrides.control.trigger.SimpleDispatchTrigger; +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.event.player.PlayerFinishedRideEvent; +import com.jverbruggen.jrides.event.ride.RideFinishedEvent; +import com.jverbruggen.jrides.logging.JRidesLogger; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.Speed; +import com.jverbruggen.jrides.models.ride.CoasterStationHandle; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.Section; +import com.jverbruggen.jrides.models.ride.section.result.BlockSectionSafetyResult; + +import javax.annotation.Nullable; +import java.util.stream.Collectors; + +public class StationTrackBehaviour extends BaseTrackBehaviour { + private final double deceleration; + private final double acceleration; + private final double driveSpeed; + + private final CoasterHandle coasterHandle; + private final JRidesLogger logger; + private Train handlingTrain; + private StationPhase phase; + private final Frame stopFrame; + private final boolean canSpawn; + private final TriggerContext triggerContext; + private final CoasterStationHandle stationHandle; + private final DispatchLock trainInStationDispatchLock; + private final DispatchLock blockSectionOccupiedDispatchLock; + private final DispatchLock restraintsLock; + + private boolean stopping; + private boolean dispatching; + + private final int passThroughCount; + private int passThroughCountState; + private final boolean forwardsDispatch; + private final byte dispatchSpeedMultiplier; + + public StationTrackBehaviour(CoasterHandle coasterHandle, CartMovementFactory cartMovementFactory, Frame stopFrame, boolean canSpawn, TriggerContext triggerContext, + CoasterStationHandle stationHandle, DispatchLock trainInStationDispatchLock, DispatchLock blockSectionOccupiedDispatchLock, + DispatchLock restraintsLock, double driveSpeed, boolean forwardsDispatch, int passThroughCount) { + super(cartMovementFactory); + this.coasterHandle = coasterHandle; + this.logger = JRidesPlugin.getLogger(); + this.deceleration = 0.2; + this.acceleration = 0.1; + this.driveSpeed = driveSpeed; + this.handlingTrain = null; + this.phase = StationPhase.IDLE; + this.stopFrame = stopFrame; + this.canSpawn = canSpawn; + this.triggerContext = triggerContext; + this.stationHandle = stationHandle; + this.dispatching = false; + this.stopping = false; + this.passThroughCount = passThroughCount; + this.passThroughCountState = passThroughCount; + + this.forwardsDispatch = forwardsDispatch; + this.dispatchSpeedMultiplier = (byte) (forwardsDispatch ? 1 : -1); + + this.trainInStationDispatchLock = trainInStationDispatchLock; + this.blockSectionOccupiedDispatchLock = blockSectionOccupiedDispatchLock; + this.restraintsLock = restraintsLock; + + trainExitedAtEnd(null, null); + } + + @Override + public TrainMovement move(Speed currentSpeed, TrainHandle trainHandle, Section section) { + Speed newSpeed = currentSpeed.clone(); + Train train = trainHandle.getTrain(); + + if(train == null) throw new RuntimeException("Train was null in StationTrackBehaviour"); + + if(handlingTrain != null && !train.equals(handlingTrain)){ + logger.warning("Train " + train.getName() + " has entered station, train is blocked"); + return null; + } + + boolean goIntoSwitch = true; + while(goIntoSwitch){ + goIntoSwitch = false; + switch (phase) { + case IDLE -> { + handlingTrain = train; + if (shouldPassThrough()) { + phase = StationPhase.PASSING_THROUGH; + passThroughCountState++; + } else if (isTrainSpeedPositive(trainHandle)) { + phase = StationPhase.ARRIVING; + } else { + phase = StationPhase.REVERSING; + } + goIntoSwitch = true; + } + case PASSING_THROUGH -> newSpeed = FreeMovementTrackBehaviour.calculateGravityActedSpeed( + trainHandle, section, currentSpeed, coasterHandle.getGravityConstant(), coasterHandle.getDragConstant() + ); + case REVERSING -> { + if (isTrainSpeedPositive(trainHandle)) { + phase = StationPhase.ARRIVING; + goIntoSwitch = true; + } else { + newSpeed.approach(acceleration, deceleration, driveSpeed); + } + } + case ARRIVING -> { + if (train.getHeadSection().hasPassed(stopFrame, train.getHeadOfTrainFrame())) { + phase = StationPhase.STOPPING; + goIntoSwitch = true; + } else { + newSpeed.approach(acceleration, deceleration, driveSpeed); + } + } + case STOPPING -> { + if (newSpeed.isZero()) { + if (!stopping) stationHandle.runEntryEffectTriggers(train); + stopping = true; + + if (!stationHandle.entryEffectTriggersDone()) break; + + phase = StationPhase.STATIONARY; + stationHandle.setStationaryTrain(train); + + if (stationHandle.isExit()) { + PlayerFinishedRideEvent.sendFinishedRideEvent(train.getPassengers() + .stream() + .map(p -> (JRidesPlayer) p) + .collect(Collectors.toList()), coasterHandle.getRide()); + RideFinishedEvent.send(coasterHandle.getRide(), train.getPassengers()); + } + + coasterHandle.getRideController().onVehicleArrive(train, stationHandle); + trainInStationDispatchLock.unlock(); + restraintsLock.setLocked(true); + train.setRestraintForAll(false); + + if (stationHandle.shouldEject()) + train.ejectPassengers(); + + stopping = false; + goIntoSwitch = true; + } else + newSpeed.minus(deceleration, 0); + } + case STATIONARY -> { + BlockSectionSafetyResult safety = getNextSectionSafety(train); + if (safety.safe()) { + blockSectionOccupiedDispatchLock.unlock(); + } else { + blockSectionOccupiedDispatchLock.lock(); + blockSectionOccupiedDispatchLock.setDebugStatus(safety.reason()); + } + SimpleDispatchTrigger dispatchTrigger = triggerContext.getDispatchTrigger(); + if (dispatching || dispatchTrigger.isActive()) { + trainInStationDispatchLock.lock(); + dispatchTrigger.reset(); + + if (!dispatching) stationHandle.runExitEffectTriggers(train); + dispatching = true; + + if (!stationHandle.exitEffectTriggersDone()) break; + + trainHandle.resetEffects(); + passThroughCountState = 0; + + phase = StationPhase.WAITING; + dispatching = false; + goIntoSwitch = true; + } + } + case WAITING -> { + Section nextSection = getNextSection(train); + if (nextSection != null && nextSection.getBlockSectionSafety(train).safe()) { + nextSection.setEntireBlockReservation(train); + phase = StationPhase.DEPARTING; + blockSectionOccupiedDispatchLock.lock(); + coasterHandle.getRideController().onVehicleDepart(train, stationHandle); + stationHandle.setStationaryTrain(null); + train.playDispatchSound(); + goIntoSwitch = true; + } + } + case DEPARTING -> newSpeed.approach( + acceleration, + acceleration, + driveSpeed*dispatchSpeedMultiplier); + } + } + + return calculateTrainMovement(train, section, newSpeed); + } + + private Section getNextSection(Train train){ + if(forwardsDispatch) return train.getNextSection(); + return train.getHeadSection().previous(train); + } + + private boolean isTrainSpeedPositive(TrainHandle trainHandle){ + return trainHandle.getSpeed().isPositive(); + } + + private boolean shouldPassThrough(){ + return this.passThroughCountState < this.passThroughCount; + } + + private void trainExited(){ + this.phase = StationPhase.IDLE; + this.handlingTrain = null; + this.stationHandle.setStationaryTrain(null); + } + + @Override + public void trainExitedAtStart(@Nullable Train train, @Nullable Section section) { + trainExited(); + } + + @Override + public void trainExitedAtEnd(@Nullable Train train, @Nullable Section section){ + trainExited(); + } + + @Override + public String getName() { + return "Station"; + } + + @Override + public boolean canBlock() { + return true; + } + + @Override + public boolean canSpawnOn() { + return canSpawn; + } + + @Override + public Frame getSpawnFrame() { + return stopFrame; + } + + @Override + protected void setParentTrackOnFrames(Track parentTrack) { + stopFrame.setTrack(parentTrack); + } +} + diff --git a/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/transfer/TrainDisplacerTransferTrackBehaviour.java b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/transfer/TrainDisplacerTransferTrackBehaviour.java new file mode 100644 index 00000000..a7f61ff9 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/coaster/trackbehaviour/transfer/TrainDisplacerTransferTrackBehaviour.java @@ -0,0 +1,303 @@ +package com.jverbruggen.jrides.animator.coaster.trackbehaviour.transfer; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.BaseTrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.CartMovementFactory; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.TrainMovement; +import com.jverbruggen.jrides.logging.LogType; +import com.jverbruggen.jrides.models.math.Matrix4x4; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.Speed; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.coaster.transfer.Transfer; +import com.jverbruggen.jrides.models.ride.coaster.transfer.TransferPosition; +import com.jverbruggen.jrides.models.ride.section.Section; +import com.jverbruggen.jrides.models.ride.section.result.BlockSectionSafetyResult; +import org.bukkit.Bukkit; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public class TrainDisplacerTransferTrackBehaviour extends BaseTrackBehaviour { + private final double deceleration; + private final double acceleration; + private final double enterDriveSpeed; + private final double exitDriveSpeed; + private final Frame stopFrame; + private final Transfer transfer; + + private TransferPhase phase; + + public TrainDisplacerTransferTrackBehaviour(CartMovementFactory cartMovementFactory, double enterDriveSpeed, double deceleration, double acceleration, double exitDriveSpeed, Frame stopFrame, Transfer transfer) { + super(cartMovementFactory); + this.deceleration = deceleration; + this.acceleration = acceleration; + this.enterDriveSpeed = enterDriveSpeed; + this.exitDriveSpeed = exitDriveSpeed; + this.stopFrame = stopFrame; + this.transfer = transfer; + this.phase = TransferPhase.IDLE; + } + + @Override + public TrainMovement move(Speed currentSpeed, TrainHandle trainHandle, Section section) { + Speed newSpeed = currentSpeed.clone(); + Train train = trainHandle.getTrain(); + + boolean goIntoSwitch = true; + while(goIntoSwitch){ + goIntoSwitch = false; + switch(phase){ + case IDLE: + phase = TransferPhase.DRIVING_UNTIL_STOP; + goIntoSwitch = true; + break; + case DRIVING_UNTIL_STOP: + if(train.getHeadSection().hasPassed(stopFrame, train.getHeadOfTrainFrame())){ + phase = TransferPhase.STOPPING; + goIntoSwitch = true; + }else{ + newSpeed.approach(acceleration, deceleration, enterDriveSpeed); + } + break; + case STOPPING: + if(newSpeed.isZero()){ + phase = TransferPhase.TRANSFERRING; + + transfer.setTrain(trainHandle); + transfer.lockTrain(); + transfer.setTargetPosition(1, true); + + goIntoSwitch = true; + } + newSpeed.minus(deceleration, 0); + break; + case TRANSFERRING: + if(transfer.hasReachedRequest()){ + phase = TransferPhase.WAITING; + goIntoSwitch = true; + } + break; + case WAITING: + Section currentSection = train.getHeadSection(); + Section goToSection = getGoToSection(train); + if(goToSection != null && goToSection.getBlockSectionSafety(train).safe()){ + transfer.unlockTrain(); + transfer.releaseRequest(); + phase = TransferPhase.DRIVING; + goIntoSwitch = true; + + boolean positiveTowardsSectionDirection = currentSection.positiveDirectionToGoTo(goToSection, train); + TransferPosition currentTransferPosition = transfer.getCurrentTransferPosition(); + + boolean isSectionForwardsType; + if(positiveTowardsSectionDirection) + isSectionForwardsType = currentTransferPosition.isSectionAtEndForwards(); + else + isSectionForwardsType = currentTransferPosition.isSectionAtStartForwards(); + + boolean trainWillBeForwards = isSectionForwardsType; + + train.setFacingForwards(trainWillBeForwards); + train.setDrivingDirection(true); + goToSection.setEntireBlockReservation(train); + } + break; + case DRIVING: + newSpeed.approach(acceleration, deceleration, exitDriveSpeed); + break; + } + } + + return calculateTrainMovement(train, section, newSpeed); + } + + private Section getGoToSection(Train train){ + Section sectionAtStart = getSectionAtStart(train, false); + Section sectionAtEnd = getSectionAtEnd(train, false); + if(sectionAtEnd != null) + return sectionAtEnd; + if(sectionAtStart != null) + return sectionAtStart; + throw new RuntimeException("No Exit section available on transfer"); + } + + @Override + public void trainExitedAtStart(@Nullable Train train, @Nullable Section section) { + throw new RuntimeException("Not supported exited train at start train displacer"); + } + + @Override + public void trainExitedAtEnd(@Nullable Train train, @Nullable Section section){ + phase = TransferPhase.IDLE; + transfer.trainExitedTransfer(); + + if(section != null){ + BlockSectionSafetyResult safetyResult = section.getBlockSectionSafety(null); + if(!safetyResult.safe()){ + JRidesPlugin.getLogger().info(LogType.SECTIONS, "Transfer Exit: Not safe for next one yet: " + safetyResult); + return; + } + } + + JRidesPlugin.getLogger().info(LogType.SECTIONS, "Transfer Exit: Safety OK"); + transfer.resetPosition(); + } + + @Override + public String getName() { + return "Transfer"; + } + + @Override + public boolean canBlock() { + return true; + } + + @Override + public boolean canSpawnOn() { + return false; + } + + @Override + public Frame getSpawnFrame() { + return null; + } + + @Override + protected void setParentTrackOnFrames(Track parentTrack) { + + } + + @Override + public boolean definesNextSection() { + return true; + } + + @Override + public Vector3 getBehaviourDefinedPosition(Vector3 originalPosition) { + Vector3 transferLocation = transfer.getCurrentLocation(); + Quaternion transferOrientation = transfer.getCurrentOrientation(); + + Vector3 offsetFromOrigin = Vector3.subtract(originalPosition, transfer.getOrigin()); + + Matrix4x4 rotationMatrix = new Matrix4x4(); + rotationMatrix.translate(transferLocation); + rotationMatrix.rotate(transferOrientation); + rotationMatrix.translate(offsetFromOrigin); + + return rotationMatrix.toVector3(); + } + + @Override + public Quaternion getBehaviourDefinedOrientation(Quaternion originalOrientation) { + Quaternion transferOrientation = transfer.getCurrentOrientation(); + return Quaternion.multiply(transferOrientation, originalOrientation); + } + + private boolean canTransferSafelyInteractWith(Train train){ + TrainHandle trainHandle = null; + if(train != null) + trainHandle = train.getHandle(); + + return transfer.canSafelyInteractWith(trainHandle); + } + + @Override + public Section getSectionAtStart(Train train, boolean process) { + if(!canTransferSafelyInteractWith(train)){ + JRidesPlugin.getLogger().info(LogType.SECTIONS, "No safe interact at start"); + return null; + } + return transfer.getCurrentTransferPosition().getSectionAtStart(); + } + + @Override + public Section getSectionAtEnd(Train train, boolean process) { + if(!canTransferSafelyInteractWith(train)){ + JRidesPlugin.getLogger().info(LogType.SECTIONS, "No safe interact at end"); + return null; + } + return transfer.getCurrentTransferPosition().getSectionAtEnd(); + } + + @Override + public Collection
getAllNextSections(Train train) { + return getAllNeighbors(train); + } + + @Override + public Collection
getAllPreviousSections(Train train) { + return getAllNeighbors(train); + } + + private Collection
getAllNeighbors(Train train){ + List
sections = new ArrayList<>(); + for(TransferPosition transferPosition : transfer.getPossiblePositions()){ + Section start = transferPosition.getSectionAtStart(); + Section end = transferPosition.getSectionAtEnd(); + if(start != null) sections.add(start); + if(end != null) sections.add(end); + } + return sections; + } + + @Override + public Section getSectionNext(Train train, boolean process) { + Section logicalNext = getSectionAtEnd(train, process); + if(logicalNext != null) { + JRidesPlugin.getLogger().info(LogType.SECTIONS, "Logical next: " + logicalNext.getName()); + return logicalNext; + } else{ + JRidesPlugin.getLogger().info(LogType.SECTIONS, "Logical next: null"); + return null; + } + } + + @Override + public Section getSectionPrevious(Train train, boolean process) { + Section logicalNext = getSectionAtStart(train, process); + if(logicalNext != null) { + JRidesPlugin.getLogger().info(LogType.SECTIONS, "Logical prev: " + logicalNext.getName()); + return logicalNext; + }else{ + JRidesPlugin.getLogger().info(LogType.SECTIONS, "Logical prev: null"); + return null; + } + } + + @Override + public boolean accepts(Train train) { + return canTransferSafelyInteractWith(train); + } + + @Override + public boolean canHandleConnections() { + return true; + } + + @Override + public boolean nextConnectsToStart() { + return transfer.getCurrentTransferPosition().isSectionAtEndConnectsToStart(); + } + + @Override + public boolean previousConnectsToStart() { + return transfer.getCurrentTransferPosition().isSectionAtStartConnectsToStart(); + } +} + +enum TransferPhase{ + IDLE, + DRIVING_UNTIL_STOP, + STOPPING, + TRANSFERRING, + WAITING, + DRIVING +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/AbstractFlatRideComponent.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/AbstractFlatRideComponent.java new file mode 100644 index 00000000..2a32a949 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/AbstractFlatRideComponent.java @@ -0,0 +1,110 @@ +package com.jverbruggen.jrides.animator.flatride; + +import com.jverbruggen.jrides.animator.flatride.attachment.Attachment; +import com.jverbruggen.jrides.animator.flatride.rotor.FlatRideModel; +import com.jverbruggen.jrides.models.math.Matrix4x4; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.ride.flatride.PlayerControl; + +import javax.annotation.Nullable; +import java.util.List; + +public abstract class AbstractFlatRideComponent implements FlatRideComponent { + private final String identifier; + private final String groupIdentifier; + private final boolean root; + private @Nullable Attachment attachedTo; + private final List flatRideModels; + + public AbstractFlatRideComponent(String identifier, String groupIdentifier, boolean root, List flatRideModels) { + this.identifier = identifier; + this.groupIdentifier = groupIdentifier; + this.root = root; + this.attachedTo = null; + this.flatRideModels = flatRideModels; + } + + @Override + public String getIdentifier() { + return identifier; + } + + @Override + public String getGroupIdentifier() { + return groupIdentifier; + } + + @Override + public boolean isRoot() { + return root; + } + + @Override + public @Nullable Attachment getAttachedTo() { + return attachedTo; + } + + @Override + public void setAttachedTo(@Nullable Attachment attachment) { + attachedTo = attachment; + } + + @Override + public Quaternion getRotation() { + Attachment attachedTo = getAttachedTo(); + if(attachedTo == null) throw new RuntimeException("Component " + identifier + " not attached to anything"); + + return attachedTo.getRotation(); + } + + @Override + public Vector3 getPosition() { + Attachment attachedTo = getAttachedTo(); + if(attachedTo == null) throw new RuntimeException("Component " + identifier + " not attached to anything"); + + return attachedTo.getPosition(); + } + + @Override + public Matrix4x4 getPositionMatrix(){ + Attachment attachedTo = getAttachedTo(); + if(attachedTo == null) throw new RuntimeException("Component " + identifier + " not attached to anything"); + + return attachedTo.getCachedMatrix(); + } + + @Override + public void tick() { + updateFlatRideModels(); + } + + @Override + public void attach(FlatRideComponent child, Quaternion offsetRotation, Vector3 offsetPosition) { + throw new RuntimeException("Cannot attach to this component"); + } + + @Nullable + @Override + public PlayerControl getPlayerControl() { + Attachment attachedTo = getAttachedTo(); + if(attachedTo == null) return null; + if(attachedTo.getParent() == null) return null; + + FlatRideComponent parent = attachedTo.getParent(); + if(parent == null) throw new RuntimeException("Expected flat ride component " + identifier + " to have parent"); + + return parent.getPlayerControl(); + } + + protected void updateFlatRideModels(){ + for(FlatRideModel flatRideModel : flatRideModels){ + flatRideModel.updateLocation(getPosition(), getRotation()); + } + } + + @Override + public boolean equalsToIdentifier(String identifier) { + return identifier.equals(this.identifier) || identifier.equals(this.groupIdentifier); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/AbstractInterconnectedFlatRideComponent.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/AbstractInterconnectedFlatRideComponent.java new file mode 100644 index 00000000..221d8c89 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/AbstractInterconnectedFlatRideComponent.java @@ -0,0 +1,61 @@ +package com.jverbruggen.jrides.animator.flatride; + +import com.jverbruggen.jrides.animator.flatride.attachment.Attachment; +import com.jverbruggen.jrides.animator.flatride.attachment.RelativeAttachment; +import com.jverbruggen.jrides.animator.flatride.rotor.FlatRideModel; +import com.jverbruggen.jrides.config.flatride.structure.attachment.joint.RelativeAttachmentJointConfig; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; + +import java.util.ArrayList; +import java.util.List; + +public abstract class AbstractInterconnectedFlatRideComponent extends AbstractFlatRideComponent { + private final List children; + private final RelativeAttachmentJointConfig joint; + + public AbstractInterconnectedFlatRideComponent(String identifier, String groupIdentifier, boolean root, RelativeAttachmentJointConfig joint, List flatRideModels) { + super(identifier, groupIdentifier, root, flatRideModels); + this.joint = joint; + this.children = new ArrayList<>(); + } + + @Override + public void attach(FlatRideComponent child, Quaternion offsetRotation, Vector3 offsetPosition){ + Attachment attachment = new RelativeAttachment(this, child, offsetRotation, offsetPosition); + + child.setAttachedTo(attachment); + children.add(attachment); + } + + @Override + public void tick() { + for(Attachment attachment : getChildren()){ + attachment.update(); + attachment.getChild().tick(); + } + + updateFlatRideModels(); + } + + @Override + public Quaternion getRotation() { + Attachment attachedTo = getAttachedTo(); + if(attachedTo == null) throw new RuntimeException("Interconnected component " + getIdentifier() + " not attached to anything"); + Quaternion rotation = attachedTo.getRotation(); + + if(joint != null && joint.anyFixed()){ + double pitch = joint.isFixedX() ? -rotation.getPitch() + joint.getFixX() : 0; + double yaw = joint.isFixedY() ? -rotation.getYaw() + joint.getFixY() : 0; + double roll = joint.isFixedZ() ? -rotation.getRoll() + joint.getFixZ() : 0; + rotation.rotateYawPitchRoll(pitch, yaw, roll); + } + + return rotation; + } + + + public List getChildren() { + return children; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/AbstractPlayerControl.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/AbstractPlayerControl.java new file mode 100644 index 00000000..e581e348 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/AbstractPlayerControl.java @@ -0,0 +1,53 @@ +package com.jverbruggen.jrides.animator.flatride; + +import com.jverbruggen.jrides.animator.flatride.rotor.controltype.ControlType; +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.models.ride.flatride.PlayerControl; +import org.bukkit.ChatColor; + +import java.util.ArrayList; +import java.util.List; + +public abstract class AbstractPlayerControl implements PlayerControl { + private List controlling; + private final ControlType controlType; + + + public AbstractPlayerControl(ControlType controlType) { + this.controlType = controlType; + this.controlling = null; + } + + @Override + public void addControlling(JRidesPlayer player) { + if(controlling == null) controlling = new ArrayList<>(); + controlling.add(player); + } + + @Override + public void removeControlling(JRidesPlayer player) { + if(controlling == null) return; + controlling.remove(player); + if(controlling.size() == 0) controlling = null; + } + + @Override + public void sendStartNotification() { + if(controlling == null) return; + + String title = controlType.getControlMessageTitle(); + String subTitle = controlType.getControlMessageSubtitle(); + + controlling.forEach( + p -> p.sendTitle(title, subTitle, 60)); + } + + public ControlType getControlType() { + return controlType; + } + + @Override + public void sendStopNotification() { + + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/ActuatorMode.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/ActuatorMode.java new file mode 100644 index 00000000..02308f1d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/ActuatorMode.java @@ -0,0 +1,6 @@ +package com.jverbruggen.jrides.animator.flatride; + +public interface ActuatorMode { + double getLowerBound(); + double getUpperBound(); +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/BlenderExportPositionRecord.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/BlenderExportPositionRecord.java new file mode 100644 index 00000000..1ee95726 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/BlenderExportPositionRecord.java @@ -0,0 +1,110 @@ +package com.jverbruggen.jrides.animator.flatride; + +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.math.VectorQuaternionState; + +public class BlenderExportPositionRecord { + private final String object; + private final int frame; + private final float posx; + private final float posy; + private final float posz; + private final float scalex; + private final float scaley; + private final float scalez; + private final float rw; + private final float rx; + private final float ry; + private final float rz; + + public BlenderExportPositionRecord(String object, int frame, float posx, float posy, float posz, float scalex, float scaley, float scalez, float rw, float rx, float ry, float rz) { + this.object = object; + this.frame = frame; + this.posx = posx; + this.posy = posy; + this.posz = posz; + this.scalex = scalex; + this.scaley = scaley; + this.scalez = scalez; + this.rw = rw; + this.rx = rx; + this.ry = ry; + this.rz = rz; + } + + public String getObject() { + return object; + } + + public int getFrame() { + return frame; + } + + public float getPosx() { + return posx; + } + + public float getPosy() { + return posy; + } + + public float getPosz() { + return posz; + } + + public float getRw() { + return rw; + } + + public float getRx() { + return rx; + } + + public float getRy() { + return ry; + } + + public float getRz() { + return rz; + } + + public Vector3 toMinecraftVector(){ + return new Vector3( + this.getPosx(), + this.getPosz(), // Minecraft Y = Blender Z + -this.getPosy()); + } + + public Quaternion toMinecraftQuaternion(){ + return new Quaternion( + this.getRx(), + this.getRz(), // Minecraft Y = Blender Z + -this.getRy(), + this.getRw()); + } + + public VectorQuaternionState toVectorQuaternionState(){ + return new VectorQuaternionState( + toMinecraftVector(), + toMinecraftQuaternion() + ); + } + + public static BlenderExportPositionRecord createFromCSVAttributes(String[] attributes){ + return new BlenderExportPositionRecord( + attributes[0], + Integer.parseInt(attributes[1]), + Float.parseFloat(attributes[2]), + Float.parseFloat(attributes[3]), + Float.parseFloat(attributes[4]), + Float.parseFloat(attributes[5]), + Float.parseFloat(attributes[6]), + Float.parseFloat(attributes[7]), + Float.parseFloat(attributes[8]), + Float.parseFloat(attributes[9]), + Float.parseFloat(attributes[10]), + Float.parseFloat(attributes[11]) + ); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/FlatRideComponent.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/FlatRideComponent.java new file mode 100644 index 00000000..ca91290a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/FlatRideComponent.java @@ -0,0 +1,223 @@ +package com.jverbruggen.jrides.animator.flatride; + +import com.jverbruggen.jrides.animator.flatride.attachment.Attachment; +import com.jverbruggen.jrides.animator.flatride.basic.StaticStructureComponent; +import com.jverbruggen.jrides.animator.flatride.linearactuator.LinearActuator; +import com.jverbruggen.jrides.animator.flatride.linearactuator.mode.LinearActuatorMode; +import com.jverbruggen.jrides.animator.flatride.rotor.FlatRideModel; +import com.jverbruggen.jrides.animator.flatride.rotor.Rotor; +import com.jverbruggen.jrides.animator.flatride.rotor.axis.RotorAxis; +import com.jverbruggen.jrides.animator.flatride.rotor.axis.RotorAxisFactory; +import com.jverbruggen.jrides.animator.flatride.rotor.mode.RotorActuatorMode; +import com.jverbruggen.jrides.animator.flatride.seat.FlatRideSeat; +import com.jverbruggen.jrides.animator.flatride.seat.SeatComponent; +import com.jverbruggen.jrides.config.coaster.objects.cart.ModelConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.LimbConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.LinearActuatorConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.RotorPlayerControlConfig; +import com.jverbruggen.jrides.config.flatride.structure.attachment.joint.RelativeAttachmentJointConfig; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.*; +import com.jverbruggen.jrides.models.ride.flatride.PlayerControl; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.viewport.ViewportManager; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; +import java.util.function.BiFunction; +import java.util.stream.Collectors; + +public interface FlatRideComponent { + String getIdentifier(); + String getGroupIdentifier(); + boolean isRoot(); + Attachment getAttachedTo(); + void setAttachedTo(Attachment attachment); + void attach(FlatRideComponent child, Quaternion offsetRotation, Vector3 offsetPosition); + Quaternion getRotation(); + Vector3 getPosition(); + Matrix4x4 getPositionMatrix(); + void tick(); + boolean equalsToIdentifier(String identifier); + @Nullable PlayerControl getPlayerControl(); + + static List findAllMatching(List components, String needle){ + return components.stream() + .filter(c -> c.equalsToIdentifier(needle)) + .collect(Collectors.toList()); + } + + private static List createDistributedComponent(String identifier, Quaternion offsetRotation, int amount, BiFunction creationFunction){ + if(amount == 1){ + return List.of(creationFunction.apply(offsetRotation.clone(), identifier)); + } + + List rotors = new ArrayList<>(); + Quaternion workingQuaternion = offsetRotation.clone(); + + for(int i = 0; i < amount; i++){ + rotors.add(creationFunction.apply(workingQuaternion.clone(), identifier + "_" + (i+1))); + + workingQuaternion.rotateY(360f/amount); + } + return rotors; + } + + static List createDistributedSeats(FlatRideHandle rideHandle, String identifier, FlatRideComponent attachedTo, Quaternion offsetRotation, Vector3 offsetPosition, int seatYawOffset, List flatRideModelsConfig, int amount){ + return createDistributedComponent( + identifier, + offsetRotation, + amount, + (seatQuaternion, seatIdentifier) -> createSeat( + rideHandle, seatIdentifier, identifier, attachedTo, seatQuaternion, offsetPosition, seatYawOffset, flatRideModelsConfig)); + } + + static List createDistributedAttachedRotors(String identifier, FlatRideComponent attachedTo, Quaternion offsetRotation, Vector3 offsetPosition, FlatRideComponentSpeed flatRideComponentSpeed, RotorActuatorMode rotorActuatorMode, RotorPlayerControlConfig controlConfig, RelativeAttachmentJointConfig jointConfig, String rotorAxisSpec, List flatRideModelsConfig, int amount){ + return createDistributedComponent( + identifier, + offsetRotation, + amount, + (rotorQuaternion, rotorIdentifier) -> FlatRideComponent.createAttachedRotor( + rotorIdentifier, identifier, attachedTo, rotorQuaternion, offsetPosition, + flatRideComponentSpeed.clone(), controlConfig, jointConfig, RotorAxisFactory.createAxisFromString(rotorAxisSpec), + rotorActuatorMode, flatRideModelsConfig)); + } + + static List createDistributedLinearActuators(FlatRideComponent attachedTo, Quaternion offsetRotation, Vector3 offsetPosition, LinearActuatorConfig linearActuatorConfig, int amount) { + return createDistributedComponent( + linearActuatorConfig.getIdentifier(), + offsetRotation, + amount, + (linearActuatorQuaternion, linearActuatorIdentifier) -> FlatRideComponent.createLinearActuator( + linearActuatorIdentifier, linearActuatorConfig.getIdentifier(), attachedTo, + linearActuatorQuaternion, offsetPosition, linearActuatorConfig.getFlatRideComponentSpeed().clone(), + linearActuatorConfig.getLinearActuatorTypeConfig().createActuatorMode(), + linearActuatorConfig.getFlatRideModels())); + } + + static List createLimb(FlatRideComponent attachedTo, Quaternion offsetRotation, Vector3 offsetPosition, LimbConfig limbConfig, VectorQuaternionState initialPose) { + return createDistributedComponent( + limbConfig.getIdentifier(), + offsetRotation, + 1, + (limbQuaternion, limbIdentifier) -> FlatRideComponent.createLimb( + limbIdentifier, limbConfig.getIdentifier(), attachedTo, + limbQuaternion, offsetPosition, limbConfig.getFlatRideModels(), initialPose)); + } + + static Rotor createAttachedRotor(String identifier, String groupIdentifier, FlatRideComponent attachedTo, Quaternion offsetRotation, Vector3 offsetPosition, FlatRideComponentSpeed flatRideComponentSpeed, RotorPlayerControlConfig controlConfig, RelativeAttachmentJointConfig jointConfig, RotorAxis rotorAxis, RotorActuatorMode actuatorMode, List flatRideModelsConfig){ + ViewportManager viewportManager = ServiceProvider.getSingleton(ViewportManager.class); + + Vector3 spawnPosition = MatrixMath.rotateTranslate( + attachedTo.getPosition(), + attachedTo.getRotation(), + offsetPosition, + offsetRotation).toVector3(); + + List flatRideModels = flatRideModelsConfig.stream() + .map(config -> config.toFlatRideModel(spawnPosition, viewportManager)) + .collect(Collectors.toList()); + + Rotor rotor = new Rotor(identifier, groupIdentifier, false, jointConfig, flatRideModels, flatRideComponentSpeed, rotorAxis, actuatorMode); + rotor.createPlayerControl(controlConfig); + attachedTo.attach(rotor, offsetRotation, offsetPosition); + + return rotor; + } + + static LinearActuator createLinearActuator(String identifier, String groupIdentifier, FlatRideComponent attachedTo, Quaternion offsetRotation, Vector3 offsetPosition, FlatRideComponentSpeed flatRideComponentSpeed, LinearActuatorMode actuatorMode, List flatRideModelsConfig){ + ViewportManager viewportManager = ServiceProvider.getSingleton(ViewportManager.class); + + Vector3 spawnPosition = MatrixMath.rotateTranslate( + attachedTo.getPosition(), + attachedTo.getRotation(), + offsetPosition, + offsetRotation).toVector3(); + + List flatRideModels = flatRideModelsConfig.stream() + .map(config -> config.toFlatRideModel(spawnPosition, viewportManager)) + .collect(Collectors.toList()); + + LinearActuator linearActuator = new LinearActuator(identifier, groupIdentifier, false, null, flatRideModels, flatRideComponentSpeed, actuatorMode); + attachedTo.attach(linearActuator, offsetRotation, offsetPosition); + + return linearActuator; + } + + static Limb createLimb(String identifier, String groupIdentifier, FlatRideComponent attachedTo, Quaternion offsetRotation, Vector3 offsetPosition, List flatRideModelsConfig, VectorQuaternionState initialPose){ + ViewportManager viewportManager = ServiceProvider.getSingleton(ViewportManager.class); + + Vector3 spawnPosition = MatrixMath.rotateTranslate( + attachedTo.getPosition(), + attachedTo.getRotation(), + offsetPosition, + offsetRotation).toVector3(); + + List flatRideModels = flatRideModelsConfig.stream() + .map(config -> config.toFlatRideModel(spawnPosition, viewportManager)) + .collect(Collectors.toList()); + + Limb limb = new Limb(identifier, groupIdentifier, false, null, flatRideModels, initialPose); + attachedTo.attach(limb, offsetRotation, offsetPosition); + + return limb; + } + + + static SeatComponent createSeat(FlatRideHandle flatRideHandle, String identifier, String groupIdentifier, FlatRideComponent attachedTo, Quaternion offsetRotation, Vector3 offsetPosition, int seatYawOffset, List flatRideModelsConfig){ + ViewportManager viewportManager = ServiceProvider.getSingleton(ViewportManager.class); + + Vector3 spawnPosition = MatrixMath.rotateTranslate( + attachedTo.getPosition(), + attachedTo.getRotation(), + offsetPosition, + offsetRotation).toVector3(); + + VirtualEntity seatEntity = viewportManager.spawnSeatEntity(spawnPosition, 0, null); + FlatRideSeat seat = new FlatRideSeat(flatRideHandle, null, seatEntity, Vector3PlusYaw.zero()); + + List flatRideModels = flatRideModelsConfig.stream() + .map(config -> { + FlatRideModel flatRideModel = config.toFlatRideModel(spawnPosition, viewportManager); + flatRideModel.getEntity().setHostSeat(seat); + return flatRideModel; + }) + .collect(Collectors.toList()); + + + Quaternion seatRotation = Quaternion.fromYawPitchRoll(0, seatYawOffset, 0); + SeatComponent component = new SeatComponent(identifier, groupIdentifier, false, flatRideModels, seat, seatRotation, flatRideHandle.getVehicle()); + seat.setParentSeatHost(component); + flatRideHandle.addSeatComponent(component); + + attachedTo.attach(component, offsetRotation, offsetPosition); + + PlayerControl playerControl = attachedTo.getPlayerControl(); + if(playerControl != null){ + seat.setPlayerControl(playerControl); + } + + return component; + } + + static StaticStructureComponent createStaticStructure(String identifier, String groupIdentifier, FlatRideComponent attachedTo, Quaternion offsetRotation, Vector3 offsetPosition, RelativeAttachmentJointConfig joint, List flatRideModelsConfig){ + ViewportManager viewportManager = ServiceProvider.getSingleton(ViewportManager.class); + + Vector3 spawnPosition = MatrixMath.rotateTranslate( + attachedTo.getPosition(), + attachedTo.getRotation(), + offsetPosition, + offsetRotation).toVector3(); + + List flatRideModels = flatRideModelsConfig.stream() + .map(config -> config.toFlatRideModel(spawnPosition, viewportManager)) + .collect(Collectors.toList()); + + StaticStructureComponent component = new StaticStructureComponent(identifier, groupIdentifier, false, joint, flatRideModels); + attachedTo.attach(component, offsetRotation, offsetPosition); + + return component; + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/FlatRideComponentSpeed.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/FlatRideComponentSpeed.java new file mode 100644 index 00000000..98c6ce4d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/FlatRideComponentSpeed.java @@ -0,0 +1,66 @@ +package com.jverbruggen.jrides.animator.flatride; + +public class FlatRideComponentSpeed { + private double speed; + private double minSpeed; + private double maxSpeed; + + public FlatRideComponentSpeed(double speed, double minSpeed, double maxSpeed) { + if(minSpeed > maxSpeed) throw new RuntimeException("Min speed has to be lower than max speed"); + else if(speed > maxSpeed) throw new RuntimeException("Speed has to be lower than max speed"); + else if(speed < minSpeed) throw new RuntimeException("Speed has to be higher than min speed"); + + this.speed = speed; + this.minSpeed = minSpeed; + this.maxSpeed = maxSpeed; + } + + public FlatRideComponentSpeed(double speed){ + this.speed = 0; + this.minSpeed = 0; + this.maxSpeed = speed; + } + + /** + * Discouraged. This is an abrupt speed change. + * Only use when absolutely necessary. + */ + public void setHard(double speed){ + this.speed = speed; + } + + public void accelerate(double acceleration){ + this.speed += acceleration; + if(this.speed > this.maxSpeed) this.speed = this.maxSpeed; + else if(this.speed < this.minSpeed) this.speed = this.minSpeed; + } + + public void accelerateTowards(double acceleration, double towards){ + if(this.speed > towards){ + this.speed -= acceleration; + if(this.speed < towards) this.speed = towards; + }else if(this.speed < towards){ + this.speed += acceleration; + if(this.speed > towards) this.speed = towards; + } + + if(this.speed > this.maxSpeed) this.speed = this.maxSpeed; + else if(this.speed < this.minSpeed) this.speed = this.minSpeed; + } + + public double getSpeed() { + return speed; + } + + public double getMinSpeed() { + return minSpeed; + } + + public double getMaxSpeed() { + return maxSpeed; + } + + public FlatRideComponentSpeed clone(){ + return new FlatRideComponentSpeed(this.speed, this.minSpeed, this.maxSpeed); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/FlatRideHandle.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/FlatRideHandle.java new file mode 100644 index 00000000..1cbb1e70 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/FlatRideHandle.java @@ -0,0 +1,198 @@ +package com.jverbruggen.jrides.animator.flatride; + +import com.jverbruggen.jrides.animator.AbstractRideHandle; +import com.jverbruggen.jrides.animator.flatride.seat.SeatComponent; +import com.jverbruggen.jrides.animator.flatride.station.FlatRideStationHandle; +import com.jverbruggen.jrides.animator.flatride.timing.TimingSequence; +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.config.coaster.objects.SoundsConfig; +import com.jverbruggen.jrides.config.ride.RideCounterMapConfigs; +import com.jverbruggen.jrides.control.controller.RideController; +import com.jverbruggen.jrides.control.trigger.DispatchTrigger; +import com.jverbruggen.jrides.control.trigger.SimpleDispatchTrigger; +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.event.player.PlayerFinishedRideEvent; +import com.jverbruggen.jrides.event.ride.RideFinishedEvent; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.ride.Ride; +import com.jverbruggen.jrides.models.ride.StationHandle; +import com.jverbruggen.jrides.models.ride.coaster.train.Vehicle; +import com.jverbruggen.jrides.models.ride.count.RideCounterRecord; +import com.jverbruggen.jrides.models.ride.gate.Gate; +import org.bukkit.World; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import javax.annotation.Nonnull; + +public class FlatRideHandle extends AbstractRideHandle { + private TimingSequence timingSequence; + private final FlatRideStationHandle stationHandle; + private final SimpleDispatchTrigger dispatchTrigger; + private final List seatComponents; + + private FlatRideState flatRideState; + + public FlatRideHandle(World world, Ride ride, boolean loaded, FlatRideStationHandle stationHandle, SoundsConfig sounds, PlayerLocation customEjectLocation, RideCounterMapConfigs rideCounterMapConfigs) { + super(world, ride, null, loaded, sounds, customEjectLocation, rideCounterMapConfigs); + this.stationHandle = stationHandle; + this.timingSequence = null; + this.dispatchTrigger = stationHandle.getTriggerContext().getDispatchTrigger(); + this.flatRideState = FlatRideState.IDLE; + this.seatComponents = new ArrayList<>(); + + stationHandle.setFlatRideHandle(this); + stationHandle.getTriggerContext().getRestraintTrigger().getLock().addEventListener(c -> this.onRestraintLockUpdateEventListener(c.isUnlocked())); + stationHandle.getEntryGates().forEach(Gate::open); + } + + @Override + public void tick() { + if(!isLoaded()) return; + + RideController rideController = getRideController(); + if(rideController.isActive()) + rideController.getControlMode().tick(); + + switch(this.flatRideState){ + case IDLE -> { + vehicleTick(); + + boolean dispatchActive = dispatchTrigger.isActive(); + if(dispatchActive){ + boolean dispatched = checkForDispatch(dispatchActive); + if(dispatched){ + stationHandle.runExitEffectTriggers(null); + this.flatRideState = FlatRideState.STARTING; + } + } + } + case STARTING -> { + if(stationHandle.exitEffectTriggersDone()){ + this.flatRideState = FlatRideState.RUNNING; + } + } + case RUNNING -> { + boolean finished = vehicleTick(); + + if(finished) { + stationHandle.runEntryEffectTriggers(null); + this.flatRideState = FlatRideState.STOPPING; + } + } + case STOPPING -> { + if(stationHandle.entryEffectTriggersDone()){ + onRideFinish(); + this.flatRideState = FlatRideState.IDLE; + } + } + } + } + + private boolean vehicleTick(){ + boolean finished = this.timingSequence.tick(); + this.stationHandle.getVehicle().tick(); + + return finished; + } + + private boolean checkForDispatch(boolean dispatchActive){ + if(dispatchActive && this.timingSequence.isIdle()){ + onRideStart(); + + Vehicle vehicle = getVehicle(); + getRideController().onVehicleDepart(vehicle, stationHandle); + vehicle.playDispatchSound(); + return true; + }else return false; + } + + private void onRideStart(){ + dispatchTrigger.reset(); + this.timingSequence.restart(); + stationHandle.getTriggerContext().getVehiclePresentLock().setLocked(true); + stationHandle.getEntryGates().forEach(Gate::close); + } + + private void onRideFinish(){ + PlayerFinishedRideEvent.sendFinishedRideEvent(getPassengers() + .stream() + .map(p -> (JRidesPlayer)p) + .collect(Collectors.toList()), getRide()); + RideFinishedEvent.send(getRide(), getPassengers()); + + stationHandle.getTriggerContext().getVehiclePresentLock().setLocked(false); + stationHandle.getTriggerContext().getRestraintTrigger().getLock().setLocked(true); + stationHandle.getVehicle().ejectPassengers(); + stationHandle.getEntryGates().forEach(Gate::open); + } + + private void onRestraintLockUpdateEventListener(boolean unlocked){ + seatComponents.forEach(c -> c.setRestraint(unlocked)); + } + + public void setTimingSequence(TimingSequence timingSequence) { + this.timingSequence = timingSequence; + } + + public void addRootComponent(FlatRideComponent component){ + stationHandle.getVehicle().addRootComponent(component); + } + + public List getRootComponents() { + return stationHandle.getVehicle().getRootComponents(); + } + + @Override + public DispatchTrigger getDispatchTrigger() { + return getFirstTriggerContext().getDispatchTrigger(); + } + + @Override + public TriggerContext getTriggerContext(@Nonnull String contextOwner) { + return getFirstTriggerContext(); + } + + @Override + public TriggerContext getFirstTriggerContext() { + return stationHandle.getTriggerContext(); + } + + @Override + public PlayerLocation getEjectLocation() { + return stationHandle.getEjectLocation(); + } + + @Override + public List getStationHandles() { + return List.of(stationHandle); + } + + @Override + public List getTopRideCounters() { + return null; + } + + @Override + public List getPassengers() { + return stationHandle.getVehicle().getPassengers(); + } + + public Vehicle getVehicle(){ + return stationHandle.getVehicle(); + } + + public void addSeatComponent(SeatComponent seatComponent){ + this.seatComponents.add(seatComponent); + } +} + +enum FlatRideState{ + IDLE, + STARTING, + RUNNING, + STOPPING +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/Limb.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/Limb.java new file mode 100644 index 00000000..fdb55a45 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/Limb.java @@ -0,0 +1,55 @@ +package com.jverbruggen.jrides.animator.flatride; + +import com.jverbruggen.jrides.animator.flatride.interfaces.Component6DOFPosition; +import com.jverbruggen.jrides.animator.flatride.rotor.FlatRideModel; +import com.jverbruggen.jrides.config.flatride.structure.attachment.joint.RelativeAttachmentJointConfig; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.math.VectorQuaternionState; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.flatride.Animation; +import com.jverbruggen.jrides.state.ride.flatride.AnimationHandle; +import com.jverbruggen.jrides.state.ride.flatride.AnimationLoader; + +import java.util.List; + +public class Limb extends AbstractInterconnectedFlatRideComponent implements Component6DOFPosition { + private Vector3 position; + private Quaternion rotation; + + public Limb(String identifier, String groupIdentifier, boolean root, RelativeAttachmentJointConfig joint, List flatRideModels, VectorQuaternionState initialPose) { + super(identifier, groupIdentifier, root, joint, flatRideModels); + position = initialPose.getVector(); + rotation = initialPose.getQuaternion(); + } + + @Override + public Vector3 getPosition() { + return Vector3.add(super.getPosition(), position); + } + + @Override + public Quaternion getRotation() { + return Quaternion.multiply(super.getRotation(), rotation); + } + + @Override + public void setPositionRotation(Vector3 position, Quaternion rotation) { + this.position = position; + this.rotation = rotation; + } + + public static VectorQuaternionState getInitialPoseFromAnimation(String preloadAnim, String limbIdentifier, FlatRideHandle rideHandle){ + VectorQuaternionState vectorQuaternionState; + if(preloadAnim != null){ + AnimationLoader animationLoader = ServiceProvider.getSingleton(AnimationLoader.class); + AnimationHandle animationHandle = animationLoader.loadFlatRideAnimation(preloadAnim, rideHandle); + Animation animation = animationHandle.getAnimation(limbIdentifier); + vectorQuaternionState = animation.getInitialPose(); + }else{ + vectorQuaternionState = VectorQuaternionState.zero(); + } + + return vectorQuaternionState; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/attachment/Attachment.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/attachment/Attachment.java new file mode 100644 index 00000000..ae06df11 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/attachment/Attachment.java @@ -0,0 +1,17 @@ +package com.jverbruggen.jrides.animator.flatride.attachment; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.models.math.Matrix4x4; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; + +import javax.annotation.Nullable; + +public interface Attachment { + Vector3 getPosition(); + Quaternion getRotation(); + Matrix4x4 getCachedMatrix(); + FlatRideComponent getChild(); + @Nullable FlatRideComponent getParent(); + void update(); +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/attachment/FixedAttachment.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/attachment/FixedAttachment.java new file mode 100644 index 00000000..e83b5b0d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/attachment/FixedAttachment.java @@ -0,0 +1,41 @@ +package com.jverbruggen.jrides.animator.flatride.attachment; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.models.math.Matrix4x4; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; + +public record FixedAttachment(FlatRideComponent child, Vector3 position, Quaternion rotation) implements Attachment { + @Override + public Vector3 getPosition() { + return position; + } + + @Override + public Quaternion getRotation() { + return rotation; + } + + @Override + public Matrix4x4 getCachedMatrix() { + Matrix4x4 matrix = new Matrix4x4(); + matrix.translate(getPosition()); + matrix.rotate(getRotation()); + return matrix; + } + + @Override + public FlatRideComponent getChild() { + return child; + } + + @Override + public FlatRideComponent getParent() { + return null; + } + + @Override + public void update() { + + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/attachment/RelativeAttachment.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/attachment/RelativeAttachment.java new file mode 100644 index 00000000..5c61483b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/attachment/RelativeAttachment.java @@ -0,0 +1,59 @@ +package com.jverbruggen.jrides.animator.flatride.attachment; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.models.math.Matrix4x4; +import com.jverbruggen.jrides.models.math.MatrixMath; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; + +public class RelativeAttachment implements Attachment { + private FlatRideComponent parent; + private FlatRideComponent child; + private Quaternion offsetRotation; + private Vector3 offsetPosition; + private Matrix4x4 cacheMatrix; + + public RelativeAttachment(FlatRideComponent parent, FlatRideComponent child, Quaternion offsetRotation, Vector3 offsetPosition) { + this.parent = parent; + this.child = child; + this.offsetRotation = offsetRotation; + this.offsetPosition = offsetPosition; + this.cacheMatrix = null; + + update(); + } + + @Override + public Vector3 getPosition() { + return cacheMatrix.toVector3(); + } + + @Override + public Quaternion getRotation() { + return cacheMatrix.getRotation(); + } + + @Override + public Matrix4x4 getCachedMatrix() { + return cacheMatrix.clone(); + } + + @Override + public FlatRideComponent getChild() { + return child; + } + + @Override + public FlatRideComponent getParent() { + return parent; + } + + @Override + public void update() { + cacheMatrix = MatrixMath.rotateTranslate( + parent.getPosition(), + parent.getRotation(), + this.offsetPosition, + this.offsetRotation); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/basic/StaticStructureComponent.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/basic/StaticStructureComponent.java new file mode 100644 index 00000000..2606ee2f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/basic/StaticStructureComponent.java @@ -0,0 +1,13 @@ +package com.jverbruggen.jrides.animator.flatride.basic; + +import com.jverbruggen.jrides.animator.flatride.AbstractInterconnectedFlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.rotor.FlatRideModel; +import com.jverbruggen.jrides.config.flatride.structure.attachment.joint.RelativeAttachmentJointConfig; + +import java.util.List; + +public class StaticStructureComponent extends AbstractInterconnectedFlatRideComponent { + public StaticStructureComponent(String identifier, String groupIdentifier, boolean root, RelativeAttachmentJointConfig joint, List flatRideModels) { + super(identifier, groupIdentifier, root, joint, flatRideModels); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/factory/FlatRideFactory.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/factory/FlatRideFactory.java new file mode 100644 index 00000000..b6145f85 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/factory/FlatRideFactory.java @@ -0,0 +1,109 @@ +package com.jverbruggen.jrides.animator.flatride.factory; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.animator.flatride.station.FlatRideStationHandle; +import com.jverbruggen.jrides.animator.flatride.timing.TimingSequence; +import com.jverbruggen.jrides.config.flatride.FlatRideConfig; +import com.jverbruggen.jrides.config.flatride.structure.StructureConfig; +import com.jverbruggen.jrides.config.flatride.structure.StructureConfigItem; +import com.jverbruggen.jrides.config.gates.GateOwnerConfigSpec; +import com.jverbruggen.jrides.config.ride.RideState; +import com.jverbruggen.jrides.control.DispatchLock; +import com.jverbruggen.jrides.control.DispatchLockCollection; +import com.jverbruggen.jrides.control.SimpleDispatchLock; +import com.jverbruggen.jrides.control.controller.RideController; +import com.jverbruggen.jrides.control.controller.RideControllerFactory; +import com.jverbruggen.jrides.control.trigger.*; +import com.jverbruggen.jrides.control.uiinterface.menu.RideControlMenuFactory; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.menu.Menu; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.ride.flatride.FlatRide; +import com.jverbruggen.jrides.models.ride.gate.Gate; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.World; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public class FlatRideFactory { + private final RideControllerFactory rideControllerFactory; + private final RideControlMenuFactory rideControlMenuFactory; + private final LanguageFile languageFile; + + public FlatRideFactory() { + rideControllerFactory = ServiceProvider.getSingleton(RideControllerFactory.class); + rideControlMenuFactory = ServiceProvider.getSingleton(RideControlMenuFactory.class); + languageFile = ServiceProvider.getSingleton(LanguageFile.class); + } + + public RideHandle createFromConfig(String rideIdentifier, World world, RideState rideState, FlatRideConfig flatRideConfig){ + String displayName = flatRideConfig.getDisplayName(); + List displayDescription = flatRideConfig.getDisplayDescription(); + ItemStack displayItem = flatRideConfig.getDisplayItem().createItemStack(); + PlayerLocation warpLocation = flatRideConfig.getWarpLocation(); + boolean canExitDuringRide = flatRideConfig.canExitDuringRide(); + String shortStationName = "station"; + + DispatchLockCollection dispatchLockCollection = new DispatchLockCollection("Main locks"); + + DispatchLock vehicleInStation = new SimpleDispatchLock(dispatchLockCollection, + languageFile.get(LanguageFileField.NOTIFICATION_RIDE_NO_TRAIN_PRESENT), false); + DispatchLock minimumWaitTimeDispatchLock = new SimpleDispatchLock(dispatchLockCollection, + languageFile.get(LanguageFileField.NOTIFICATION_RIDE_WAITING_TIME), true); + DispatchLock restraintLock = new SimpleDispatchLock(dispatchLockCollection, + languageFile.get(LanguageFileField.NOTIFICATION_RIDE_RESTRAINTS_NOT_CLOSED), true); + DispatchLockCollection gatesGenericLock = new DispatchLockCollection( + languageFile.get(LanguageFileField.NOTIFICATION_RIDE_GATES_NOT_CLOSED), dispatchLockCollection); + + TriggerContext triggerContext = new TriggerContext( + dispatchLockCollection, + vehicleInStation, + new SimpleDispatchTrigger(dispatchLockCollection), + new GateTrigger(gatesGenericLock), + new RestraintTrigger(restraintLock)); + + Optional optionalGateOwner = flatRideConfig.getGates().getGateOwnerSpec(shortStationName); + List gates = optionalGateOwner.isPresent() + ? optionalGateOwner.get().createGates(shortStationName, world, gatesGenericLock) + : new ArrayList<>(); + + + FlatRideStationHandle stationHandle = flatRideConfig.getStationConfig().createFlatRideStationHandle( + rideIdentifier, + displayName + "_" + shortStationName, shortStationName, triggerContext, gates, minimumWaitTimeDispatchLock + ); + + FlatRide flatRide = new FlatRide(rideIdentifier, displayName, displayDescription, displayItem, + warpLocation, canExitDuringRide); + FlatRideHandle flatRideHandle = new FlatRideHandle(world, flatRide, true, stationHandle, flatRideConfig.getSoundsConfig(), flatRideConfig.getCustomEjectLocation(), flatRideConfig.getRideCounterMapConfigs()); + + flatRideConfig.getInteractionEntities().spawnEntities(flatRideHandle); + + List components = new ArrayList<>(); + + StructureConfig structureConfig = flatRideConfig.getStructureConfig(); + for(StructureConfigItem item : structureConfig.getItems()){ + item.createAndAddTo(components, flatRideHandle); + } + + components.stream() + .filter(FlatRideComponent::isRoot) + .forEach(flatRideHandle::addRootComponent); + + TimingSequence timingSequence = flatRideConfig.getTimingConfig().createTimingSequence(flatRideHandle, components); + flatRideHandle.setTimingSequence(timingSequence); + + RideController rideController = rideControllerFactory.createFlatRideController(flatRideHandle); + Menu rideControlMenu = rideControlMenuFactory.getRideControlMenu(rideController, null); + flatRideHandle.setRideController(rideController, rideControlMenu); + + flatRideHandle.setState(rideState); + return flatRideHandle; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/interfaces/Component6DOFPosition.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/interfaces/Component6DOFPosition.java new file mode 100644 index 00000000..7712054e --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/interfaces/Component6DOFPosition.java @@ -0,0 +1,8 @@ +package com.jverbruggen.jrides.animator.flatride.interfaces; + +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; + +public interface Component6DOFPosition { + void setPositionRotation(Vector3 position, Quaternion rotation); +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/interfaces/HasPosition.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/interfaces/HasPosition.java new file mode 100644 index 00000000..a1c4d737 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/interfaces/HasPosition.java @@ -0,0 +1,17 @@ +package com.jverbruggen.jrides.animator.flatride.interfaces; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponentSpeed; + +public interface HasPosition extends HasSpeed { + void setInstructionPosition(double position); + + double getInstructionPosition(); + + double getLowerOperatingRange(); + double getUpperOperatingRange(); + + void setLowerOperatingRange(double lower); + void setUpperOperatingRange(double upper); + + void goTowards(double targetPosition, double fromPosition, double acceleration, FlatRideComponentSpeed componentSpeed); +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/interfaces/HasSpeed.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/interfaces/HasSpeed.java new file mode 100644 index 00000000..b5af6319 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/interfaces/HasSpeed.java @@ -0,0 +1,8 @@ +package com.jverbruggen.jrides.animator.flatride.interfaces; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideComponentSpeed; + +public interface HasSpeed extends FlatRideComponent { + FlatRideComponentSpeed getFlatRideComponentSpeed(); +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/interfaces/PlayerControllable.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/interfaces/PlayerControllable.java new file mode 100644 index 00000000..4d828840 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/interfaces/PlayerControllable.java @@ -0,0 +1,8 @@ +package com.jverbruggen.jrides.animator.flatride.interfaces; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; + +public interface PlayerControllable extends FlatRideComponent { + boolean allowsControl(); + void setAllowControl(boolean allow); +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/linearactuator/LinearActuator.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/linearactuator/LinearActuator.java new file mode 100644 index 00000000..217c97db --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/linearactuator/LinearActuator.java @@ -0,0 +1,83 @@ +package com.jverbruggen.jrides.animator.flatride.linearactuator; + +import com.jverbruggen.jrides.animator.flatride.AbstractInterconnectedFlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideComponentSpeed; +import com.jverbruggen.jrides.animator.flatride.attachment.Attachment; +import com.jverbruggen.jrides.animator.flatride.interfaces.HasPosition; +import com.jverbruggen.jrides.animator.flatride.linearactuator.mode.LinearActuatorMode; +import com.jverbruggen.jrides.animator.flatride.rotor.FlatRideModel; +import com.jverbruggen.jrides.config.flatride.structure.attachment.joint.RelativeAttachmentJointConfig; +import com.jverbruggen.jrides.models.math.Vector3; + +import java.util.List; + +public class LinearActuator extends AbstractInterconnectedFlatRideComponent implements HasPosition { + private final FlatRideComponentSpeed flatRideComponentSpeed; + private final Vector3 actuatorState; + private final LinearActuatorMode actuatorMode; + + public LinearActuator(String identifier, String groupIdentifier, boolean root, RelativeAttachmentJointConfig joint, List flatRideModels, FlatRideComponentSpeed flatRideComponentSpeed, LinearActuatorMode actuatorMode) { + super(identifier, groupIdentifier, root, joint, flatRideModels); + this.flatRideComponentSpeed = flatRideComponentSpeed; + + this.actuatorState = new Vector3(0,0,0); + this.actuatorMode = actuatorMode; + } + + @Override + public Vector3 getPosition() { + return Vector3.add(super.getPosition(), actuatorState); + } + + @Override + public void tick() { + actuatorMode.tick(flatRideComponentSpeed, actuatorState); + + for(Attachment attachment : getChildren()){ + attachment.update(); + attachment.getChild().tick(); + } + + updateFlatRideModels(); + } + + @Override + public FlatRideComponentSpeed getFlatRideComponentSpeed() { + return flatRideComponentSpeed; + } + + @Override + public void setInstructionPosition(double position) { + actuatorMode.setPosition(actuatorState, position); + } + + @Override + public double getInstructionPosition() { + return actuatorMode.getPosition(actuatorState); + } + + @Override + public double getLowerOperatingRange() { + return actuatorMode.getLowerBound(); + } + + @Override + public double getUpperOperatingRange() { + return actuatorMode.getUpperBound(); + } + + @Override + public void setLowerOperatingRange(double lower) { + throw new RuntimeException("Cannot set operating range for linear actuator"); + } + + @Override + public void setUpperOperatingRange(double upper) { + throw new RuntimeException("Cannot set operating range for linear actuator"); + } + + @Override + public void goTowards(double targetPosition, double fromPosition, double acceleration, FlatRideComponentSpeed componentSpeed) { + componentSpeed.accelerate(acceleration); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/linearactuator/mode/ContinuousMode.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/linearactuator/mode/ContinuousMode.java new file mode 100644 index 00000000..ae45841c --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/linearactuator/mode/ContinuousMode.java @@ -0,0 +1,48 @@ +package com.jverbruggen.jrides.animator.flatride.linearactuator.mode; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponentSpeed; +import com.jverbruggen.jrides.models.math.Vector3; + +public class ContinuousMode implements LinearActuatorMode { + private final Double lowerBound; + private final Double upperBound; + + public ContinuousMode(Double lowerBound, Double upperBound) { + this.lowerBound = lowerBound; + this.upperBound = upperBound; + } + + public void tick(FlatRideComponentSpeed flatRideComponentSpeed, Vector3 actuatorState){ + double currentSpeed = flatRideComponentSpeed.getSpeed(); + actuatorState.y += currentSpeed; + + // TODO: implement braking + if(upperBound != null && currentSpeed >= 0 && actuatorState.y > upperBound){ + actuatorState.y = upperBound; + flatRideComponentSpeed.setHard(0); + }else if(lowerBound != null && currentSpeed < 0 && actuatorState.y < lowerBound){ + actuatorState.y = lowerBound; + flatRideComponentSpeed.setHard(0); + } + } + + @Override + public double getPosition(Vector3 actuatorState) { + return actuatorState.y; + } + + @Override + public void setPosition(Vector3 actuatorState, double position) { + actuatorState.y = position; + } + + @Override + public double getLowerBound() { + return lowerBound; + } + + @Override + public double getUpperBound() { + return upperBound; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/linearactuator/mode/LinearActuatorMode.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/linearactuator/mode/LinearActuatorMode.java new file mode 100644 index 00000000..380b33f3 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/linearactuator/mode/LinearActuatorMode.java @@ -0,0 +1,11 @@ +package com.jverbruggen.jrides.animator.flatride.linearactuator.mode; + +import com.jverbruggen.jrides.animator.flatride.ActuatorMode; +import com.jverbruggen.jrides.animator.flatride.FlatRideComponentSpeed; +import com.jverbruggen.jrides.models.math.Vector3; + +public interface LinearActuatorMode extends ActuatorMode { + void tick(FlatRideComponentSpeed flatRideComponentSpeed, Vector3 actuatorState); + double getPosition(Vector3 actuatorState); + void setPosition(Vector3 actuatorState, double position); +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/linearactuator/mode/LinearActuatorModeEnum.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/linearactuator/mode/LinearActuatorModeEnum.java new file mode 100644 index 00000000..f4a49d42 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/linearactuator/mode/LinearActuatorModeEnum.java @@ -0,0 +1,14 @@ +package com.jverbruggen.jrides.animator.flatride.linearactuator.mode; + +public enum LinearActuatorModeEnum { + CONTINUOUS, + SINE; + + public static LinearActuatorModeEnum from(String s) { + return switch (s) { + case "continuous" -> CONTINUOUS; + case "sine" -> SINE; + default -> throw new IllegalStateException("Unexpected value: " + s); + }; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/linearactuator/mode/SineMode.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/linearactuator/mode/SineMode.java new file mode 100644 index 00000000..51752ce9 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/linearactuator/mode/SineMode.java @@ -0,0 +1,57 @@ +package com.jverbruggen.jrides.animator.flatride.linearactuator.mode; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponentSpeed; +import com.jverbruggen.jrides.models.math.Vector3; + +public class SineMode implements LinearActuatorMode { + private static final float PI = 3.1415926535f; + private static final float PI2 = PI*2; + + private final float size; + private final short phase; + private double sineState; + + public SineMode(float size, short phase) { + this.size = size; + this.phase = phase; + + resetToInitialPhase(); + } + + public void tick(FlatRideComponentSpeed flatRideComponentSpeed, Vector3 actuatorState){ + increaseSineState(flatRideComponentSpeed, actuatorState); + } + + @Override + public double getPosition(Vector3 actuatorState) { + return sineState; + } + + @Override + public void setPosition(Vector3 actuatorState, double position) { + this.updateActuatorState(actuatorState, position); + } + + @Override + public double getLowerBound() { + return 0; + } + + @Override + public double getUpperBound() { + return PI2; + } + + private void resetToInitialPhase(){ + this.sineState = phase/180f*PI; + } + + private void increaseSineState(FlatRideComponentSpeed flatRideComponentSpeed, Vector3 actuatorState){ + sineState = (sineState + flatRideComponentSpeed.getSpeed()/180*PI) % PI2; + updateActuatorState(actuatorState, this.sineState); + } + + private void updateActuatorState(Vector3 actuatorState, double sineState){ + actuatorState.y = Math.sin(sineState)*size; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/FlatRideModel.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/FlatRideModel.java new file mode 100644 index 00000000..a195752a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/FlatRideModel.java @@ -0,0 +1,29 @@ +package com.jverbruggen.jrides.animator.flatride.rotor; + +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Matrix4x4; +import com.jverbruggen.jrides.models.math.MatrixMath; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; + +public class FlatRideModel { + private final VirtualEntity entity; + private final Vector3 offset; + private final Quaternion rotationOffset; + + public FlatRideModel(VirtualEntity entity, Vector3 offset, Quaternion rotationOffset) { + this.entity = entity; + this.offset = offset; + this.rotationOffset = rotationOffset; + } + + public void updateLocation(Vector3 parentLocation, Quaternion parentRotation){ + Matrix4x4 matrix = MatrixMath.rotateTranslate(parentLocation, parentRotation, offset, rotationOffset); + entity.setLocation(matrix.toVector3()); + entity.setRotation(matrix.getRotation()); + } + + public VirtualEntity getEntity() { + return entity; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/Rotor.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/Rotor.java new file mode 100644 index 00000000..571a86f1 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/Rotor.java @@ -0,0 +1,188 @@ +package com.jverbruggen.jrides.animator.flatride.rotor; + +import com.jverbruggen.jrides.animator.flatride.AbstractInterconnectedFlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideComponentSpeed; +import com.jverbruggen.jrides.animator.flatride.attachment.Attachment; +import com.jverbruggen.jrides.animator.flatride.interfaces.HasPosition; +import com.jverbruggen.jrides.animator.flatride.interfaces.PlayerControllable; +import com.jverbruggen.jrides.animator.flatride.rotor.axis.RotorAxis; +import com.jverbruggen.jrides.animator.flatride.rotor.mode.RotorActuatorMode; +import com.jverbruggen.jrides.config.flatride.structure.actuator.RotorPlayerControlConfig; +import com.jverbruggen.jrides.config.flatride.structure.attachment.joint.RelativeAttachmentJointConfig; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.SpeedUtil; +import com.jverbruggen.jrides.models.ride.flatride.PlayerControl; + +import javax.annotation.Nullable; +import java.util.List; + +public class Rotor extends AbstractInterconnectedFlatRideComponent implements PlayerControllable, HasPosition { + private final FlatRideComponentSpeed flatRideComponentSpeed; + private final RotorAxis rotorAxis; + private RotorPlayerControl playerControl; + private boolean allowsControlState; + private double lowerOperatingRange; + private double upperOperatingRange; + private final RotorActuatorMode actuatorMode; + + public Rotor(String identifier, String groupIdentifier, boolean root, RelativeAttachmentJointConfig joint, List flatRideModels, FlatRideComponentSpeed flatRideComponentSpeed, RotorAxis rotorAxis, RotorActuatorMode actuatorMode) { + super(identifier, groupIdentifier, root, joint, flatRideModels); + this.rotorAxis = rotorAxis; + this.actuatorMode = actuatorMode; + this.playerControl = null; + this.flatRideComponentSpeed = flatRideComponentSpeed; + this.allowsControlState = false; + this.lowerOperatingRange = 0; + this.upperOperatingRange = 360; + } + + @Override + public Quaternion getRotation() { + Attachment attachedTo = getAttachedTo(); + if(attachedTo == null) throw new RuntimeException("Rotor " + getIdentifier() + " not attached to anything"); + + return Quaternion.multiply(attachedTo.getRotation(), rotorAxis.getQuaternion()); + } + + public FlatRideComponentSpeed getFlatRideComponentSpeed() { + return flatRideComponentSpeed; + } + + @Override + public void tick() { + if(allowsControl()){ + playerControl.apply(); + } + + actuatorMode.tick(flatRideComponentSpeed, rotorAxis); + + for(Attachment attachment : getChildren()){ + attachment.update(); + attachment.getChild().tick(); + } + + updateFlatRideModels(); + } + + @Override + public boolean allowsControl() { + return this.allowsControlState; + } + + @Override + public void setAllowControl(boolean allow) { + if(this.allowsControlState == allow) return; + + if(allow){ + playerControl.reset(); + playerControl.sendStartNotification(); + } + this.allowsControlState = allow; + } + + @Nullable + @Override + public PlayerControl getPlayerControl() { + if(playerControl != null) + return playerControl; + + return super.getPlayerControl(); + } + + public void createPlayerControl(RotorPlayerControlConfig controlConfig){ + if(controlConfig == null) return; + + playerControl = controlConfig.createPlayerControl(); + playerControl.setRotor(this); + } + + public double getRotorRotation(){ + return rotorAxis.getRotation(); + } + + public void setRotorRotation(double toValue){ + rotorAxis.setRotation(toValue); + } + + @Override + public void setInstructionPosition(double position) { + setRotorRotation(position); + } + + @Override + public double getInstructionPosition() { + return getRotorRotation(); + } + + @Override + public double getLowerOperatingRange() { + return lowerOperatingRange; + } + + @Override + public double getUpperOperatingRange() { + return upperOperatingRange; + } + + @Override + public void setLowerOperatingRange(double lower) { + lowerOperatingRange = lower; + } + + @Override + public void setUpperOperatingRange(double upper) { + upperOperatingRange = upper; + } + + @Override + public void goTowards(double targetPosition, double fromPosition, double acceleration, FlatRideComponentSpeed componentSpeed) { + double currentSpeed = componentSpeed.getSpeed(); + double currentPosition = this.getInstructionPosition(); + double absAcceleration = Math.abs(acceleration); + double maxSpeed = componentSpeed.getMaxSpeed(); + double minSpeed = componentSpeed.getMinSpeed(); + + boolean positiveAcceleration = acceleration >= 0; + boolean goingForwards = currentSpeed > 0 || (currentSpeed == 0 && positiveAcceleration); + + double breakPosition = SpeedUtil.positionStartBraking( + currentSpeed, + goingForwards ? -absAcceleration : absAcceleration, + targetPosition, + 0); + +// JRidesPlugin.getLogger().debug("s: " + currentSpeed + "(" + goingForwards + ") a: " + acceleration); +// JRidesPlugin.getLogger().debug("f: " + fromPositionAcc + " c: " + hasPosition.getInstructionPosition() + " t: " + targetPositionAcc + " b: " + breakPosition); + + double margin = 0.1; + + boolean shouldBreak = SpeedUtil.hasPassed(fromPosition, this.getInstructionPosition(), breakPosition, + positiveAcceleration, margin); + boolean shouldHardBreak = SpeedUtil.hasPassed(fromPosition, this.getInstructionPosition(), targetPosition, + goingForwards, absAcceleration); + +// JRidesPlugin.getLogger().debug("break: " + shouldBreak + " hard: " + shouldHardBreak + "\n----"); + + if(shouldHardBreak){ + componentSpeed.setHard(0); + if(Math.abs(targetPosition - this.getInstructionPosition()) < margin) + this.setInstructionPosition(targetPosition); + }else if(shouldBreak){ + componentSpeed.accelerateTowards(absAcceleration, 0); + this.checkBump(currentPosition, componentSpeed, fromPosition, targetPosition, positiveAcceleration); + }else{ + double targetSpeed = positiveAcceleration ? maxSpeed : minSpeed; + + componentSpeed.accelerateTowards(absAcceleration, targetSpeed); + this.checkBump(currentPosition, componentSpeed, fromPosition, targetPosition, positiveAcceleration); + } + } + + private void checkBump(double currentPosition, FlatRideComponentSpeed componentSpeed, double fromPosition, double targetPosition, boolean positiveSpeed){ + double newPosition = currentPosition + componentSpeed.getSpeed(); + if(SpeedUtil.hasPassed(fromPosition, newPosition, targetPosition, positiveSpeed, 0d)){ + componentSpeed.setHard(0); + this.setInstructionPosition(targetPosition); + } + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/RotorPlayerControl.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/RotorPlayerControl.java new file mode 100644 index 00000000..33e6833f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/RotorPlayerControl.java @@ -0,0 +1,7 @@ +package com.jverbruggen.jrides.animator.flatride.rotor; + +import com.jverbruggen.jrides.models.ride.flatride.PlayerControl; + +public interface RotorPlayerControl extends PlayerControl { + void setRotor(Rotor rotor); +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/RotorSpeedPlayerControl.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/RotorSpeedPlayerControl.java new file mode 100644 index 00000000..8655e784 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/RotorSpeedPlayerControl.java @@ -0,0 +1,64 @@ +package com.jverbruggen.jrides.animator.flatride.rotor; + +import com.jverbruggen.jrides.animator.flatride.AbstractPlayerControl; +import com.jverbruggen.jrides.animator.flatride.rotor.controltype.ControlType; +import com.jverbruggen.jrides.models.ride.seat.InstructionType; + +public class RotorSpeedPlayerControl extends AbstractPlayerControl implements RotorPlayerControl { + private Rotor rotor; + private final double lowerSpeed; + private final double upperSpeed; + private final double accelerate; + + private double currentSpeed; + private double pendingAcceleration; + + public RotorSpeedPlayerControl(double lowerSpeed, double upperSpeed, double accelerate, ControlType controlType) { + super(controlType); + this.rotor = null; + this.lowerSpeed = lowerSpeed; + this.upperSpeed = upperSpeed; + this.accelerate = accelerate; + this.currentSpeed = 0f; + this.pendingAcceleration = 0f; + } + + public void setRotor(Rotor rotor) { + this.rotor = rotor; + this.currentSpeed = this.rotor.getFlatRideComponentSpeed().getSpeed(); + } + + @Override + public void processInstructionAsync(InstructionType instruction) { + if(!rotor.allowsControl()) return; + + pendingAcceleration = getControlType().processInstruction(instruction, accelerate); + } + + @Override + public void apply() { + double acceleration = this.pendingAcceleration; // Synchronization? + + currentSpeed = rotor.getFlatRideComponentSpeed().getSpeed(); + double oldSpeed = currentSpeed; + currentSpeed += acceleration; + if(currentSpeed > upperSpeed){ + currentSpeed = upperSpeed; + acceleration = upperSpeed - oldSpeed; + } + else if(currentSpeed < lowerSpeed){ + currentSpeed = lowerSpeed; + acceleration = lowerSpeed - oldSpeed; + } + + rotor.getFlatRideComponentSpeed().accelerate(acceleration); + this.pendingAcceleration = 0; + } + + @Override + public void reset() { + this.pendingAcceleration = 0; + this.currentSpeed = rotor.getFlatRideComponentSpeed().getSpeed(); + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/RotorTargetPositionPlayerControl.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/RotorTargetPositionPlayerControl.java new file mode 100644 index 00000000..e846a5bd --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/RotorTargetPositionPlayerControl.java @@ -0,0 +1,57 @@ +package com.jverbruggen.jrides.animator.flatride.rotor; + +import com.jverbruggen.jrides.animator.flatride.AbstractPlayerControl; +import com.jverbruggen.jrides.animator.flatride.rotor.controltype.ControlType; +import com.jverbruggen.jrides.animator.flatride.timing.instruction.towards.TowardsPositionInstruction; +import com.jverbruggen.jrides.models.ride.seat.InstructionType; + +public class RotorTargetPositionPlayerControl extends AbstractPlayerControl implements RotorPlayerControl { + private Rotor rotor; + private final double lowerPosition; + private final double upperPosition; + private final double acceleration; + private final double margin; + + private double pendingAcceleration; + + public RotorTargetPositionPlayerControl(double lowerPosition, double upperPosition, double acceleration, ControlType controlType) { + super(controlType); + this.rotor = null; + this.lowerPosition = lowerPosition; + this.upperPosition = upperPosition; + this.acceleration = acceleration; + this.margin = 2*this.acceleration; + this.pendingAcceleration = 0f; + } + + public void setRotor(Rotor rotor) { + this.rotor = rotor; + rotor.setLowerOperatingRange(lowerPosition); + rotor.setUpperOperatingRange(upperPosition); + } + + @Override + public void processInstructionAsync(InstructionType instruction) { + if(!rotor.allowsControl()) return; + + pendingAcceleration = getControlType().processInstruction(instruction, acceleration); + } + + @Override + public void apply() { + TowardsPositionInstruction.run( + rotor, + this.pendingAcceleration, + this.lowerPosition, + this.upperPosition, + this.margin, + rotor.getFlatRideComponentSpeed().getMaxSpeed(), + rotor.getFlatRideComponentSpeed().getMinSpeed()); + } + + @Override + public void reset() { + this.pendingAcceleration = 0; + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/axis/RotorAxis.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/axis/RotorAxis.java new file mode 100644 index 00000000..c526108d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/axis/RotorAxis.java @@ -0,0 +1,10 @@ +package com.jverbruggen.jrides.animator.flatride.rotor.axis; + +import com.jverbruggen.jrides.models.math.Quaternion; + +public interface RotorAxis { + void setRotation(double toValue); + void addRotation(double addValue); + double getRotation(); + Quaternion getQuaternion(); +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/axis/RotorAxisFactory.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/axis/RotorAxisFactory.java new file mode 100644 index 00000000..5cc2652b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/axis/RotorAxisFactory.java @@ -0,0 +1,25 @@ +package com.jverbruggen.jrides.animator.flatride.rotor.axis; + +public class RotorAxisFactory { + public static RotorAxis createAxisX(){ + return new RotorAxisX(); + } + + public static RotorAxis createAxisY(){ + return new RotorAxisY(); + } + + public static RotorAxis createAxisZ(){ + return new RotorAxisZ(); + } + + public static RotorAxis createAxisFromString(String rotorAxis){ + if(rotorAxis.equalsIgnoreCase("x")) + return createAxisX(); + else if(rotorAxis.equalsIgnoreCase("y")) + return createAxisY(); + else if(rotorAxis.equalsIgnoreCase("z")) + return createAxisZ(); + else throw new RuntimeException("Unknown axis " + rotorAxis); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/axis/RotorAxisX.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/axis/RotorAxisX.java new file mode 100644 index 00000000..002d39e2 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/axis/RotorAxisX.java @@ -0,0 +1,15 @@ +package com.jverbruggen.jrides.animator.flatride.rotor.axis; + +import com.jverbruggen.jrides.models.math.Quaternion; + +public class RotorAxisX extends RotorAxisY { + @Override + public void addRotation(double addValue) { + add(addValue); + } + + @Override + public Quaternion getQuaternion() { + return Quaternion.fromYawPitchRoll(getRotation(), 0, 0); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/axis/RotorAxisY.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/axis/RotorAxisY.java new file mode 100644 index 00000000..f4b9775a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/axis/RotorAxisY.java @@ -0,0 +1,39 @@ +package com.jverbruggen.jrides.animator.flatride.rotor.axis; + +import com.jverbruggen.jrides.models.math.MathUtil; +import com.jverbruggen.jrides.models.math.Quaternion; + +public class RotorAxisY implements RotorAxis { + private double value; + + public RotorAxisY() { + this.value = 0; + } + + protected void add(double value){ + this.value = MathUtil.floorMod(this.value + value, 360d); + } + + @Override + public void setRotation(double toValue){ + double fromRotation = getRotation(); + if(fromRotation == toValue) return; + + addRotation(toValue - fromRotation); + } + + @Override + public void addRotation(double addValue) { + add(addValue); + } + + @Override + public double getRotation() { + return this.value; + } + + @Override + public Quaternion getQuaternion() { + return Quaternion.fromYawPitchRoll(0, this.value, 0); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/axis/RotorAxisZ.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/axis/RotorAxisZ.java new file mode 100644 index 00000000..2f95591c --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/axis/RotorAxisZ.java @@ -0,0 +1,15 @@ +package com.jverbruggen.jrides.animator.flatride.rotor.axis; + +import com.jverbruggen.jrides.models.math.Quaternion; + +public class RotorAxisZ extends RotorAxisY { + @Override + public void addRotation(double addValue) { + add(addValue); + } + + @Override + public Quaternion getQuaternion() { + return Quaternion.fromYawPitchRoll(0, 0, getRotation()); + } +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/controltype/ADControl.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/controltype/ADControl.java new file mode 100644 index 00000000..a0f7f618 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/controltype/ADControl.java @@ -0,0 +1,26 @@ +package com.jverbruggen.jrides.animator.flatride.rotor.controltype; + +import com.jverbruggen.jrides.models.ride.seat.InstructionType; +import org.bukkit.ChatColor; + +public class ADControl implements ControlType { + @Override + public double processInstruction(InstructionType instruction, double data) { + if(instruction == InstructionType.A){ + return -data; + }else if(instruction == InstructionType.D){ + return data; + } + else return 0; + } + + @Override + public String getControlMessageTitle() { + return ChatColor.RED + "Take Control!"; + } + + @Override + public String getControlMessageSubtitle() { + return ChatColor.GOLD + "Press A or D"; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/controltype/ControlType.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/controltype/ControlType.java new file mode 100644 index 00000000..a016bfa5 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/controltype/ControlType.java @@ -0,0 +1,9 @@ +package com.jverbruggen.jrides.animator.flatride.rotor.controltype; + +import com.jverbruggen.jrides.models.ride.seat.InstructionType; + +public interface ControlType { + double processInstruction(InstructionType instruction, double data); + String getControlMessageTitle(); + String getControlMessageSubtitle(); +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/controltype/SpaceBarControl.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/controltype/SpaceBarControl.java new file mode 100644 index 00000000..8528ea7b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/controltype/SpaceBarControl.java @@ -0,0 +1,24 @@ +package com.jverbruggen.jrides.animator.flatride.rotor.controltype; + +import com.jverbruggen.jrides.models.ride.seat.InstructionType; +import org.bukkit.ChatColor; + +public class SpaceBarControl implements ControlType { + @Override + public double processInstruction(InstructionType instruction, double data) { + if(instruction == InstructionType.SPACE){ + return data; + } + else return -data; + } + + @Override + public String getControlMessageTitle() { + return ChatColor.RED + "Take Control!"; + } + + @Override + public String getControlMessageSubtitle() { + return ChatColor.GOLD + "Press Space"; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/controltype/WSControl.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/controltype/WSControl.java new file mode 100644 index 00000000..1aca9dad --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/controltype/WSControl.java @@ -0,0 +1,26 @@ +package com.jverbruggen.jrides.animator.flatride.rotor.controltype; + +import com.jverbruggen.jrides.models.ride.seat.InstructionType; +import org.bukkit.ChatColor; + +public class WSControl implements ControlType { + @Override + public double processInstruction(InstructionType instruction, double data) { + if(instruction == InstructionType.W){ + return data; + }else if(instruction == InstructionType.S){ + return -data; + } + else return 0; + } + + @Override + public String getControlMessageTitle() { + return ChatColor.RED + "Take Control!"; + } + + @Override + public String getControlMessageSubtitle() { + return ChatColor.GOLD + "Press W or S"; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/mode/ContinuousMode.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/mode/ContinuousMode.java new file mode 100644 index 00000000..3fee4e36 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/mode/ContinuousMode.java @@ -0,0 +1,39 @@ +package com.jverbruggen.jrides.animator.flatride.rotor.mode; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponentSpeed; +import com.jverbruggen.jrides.animator.flatride.rotor.axis.RotorAxis; + +public class ContinuousMode implements RotorActuatorMode { + private final Double lowerBound; + private final Double upperBound; + + public ContinuousMode(Double lowerBound, Double upperBound) { + this.lowerBound = lowerBound; + this.upperBound = upperBound; + } + + public void tick(FlatRideComponentSpeed flatRideComponentSpeed, RotorAxis rotorAxis){ + rotorAxis.addRotation(flatRideComponentSpeed.getSpeed()); + } + + @Override + public double getRotation(RotorAxis rotorAxis) { + return rotorAxis.getRotation(); + } + + @Override + public void setRotation(RotorAxis rotorAxis, double position) { + rotorAxis.setRotation(position); + } + + @Override + public double getLowerBound() { + return lowerBound; + } + + @Override + public double getUpperBound() { + return upperBound; + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/mode/RotorActuatorMode.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/mode/RotorActuatorMode.java new file mode 100644 index 00000000..787b3ac2 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/mode/RotorActuatorMode.java @@ -0,0 +1,11 @@ +package com.jverbruggen.jrides.animator.flatride.rotor.mode; + +import com.jverbruggen.jrides.animator.flatride.ActuatorMode; +import com.jverbruggen.jrides.animator.flatride.FlatRideComponentSpeed; +import com.jverbruggen.jrides.animator.flatride.rotor.axis.RotorAxis; + +public interface RotorActuatorMode extends ActuatorMode { + void tick(FlatRideComponentSpeed flatRideComponentSpeed, RotorAxis rotorAxis); + double getRotation(RotorAxis rotorAxis); + void setRotation(RotorAxis rotorAxis, double position); +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/mode/RotorModeEnum.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/mode/RotorModeEnum.java new file mode 100644 index 00000000..b3a8debd --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/mode/RotorModeEnum.java @@ -0,0 +1,14 @@ +package com.jverbruggen.jrides.animator.flatride.rotor.mode; + +public enum RotorModeEnum { + CONTINUOUS, + SINE; + + public static RotorModeEnum from(String s) { + return switch (s) { + case "continuous" -> CONTINUOUS; + case "sine" -> SINE; + default -> throw new IllegalStateException("Unexpected value: " + s); + }; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/mode/SineMode.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/mode/SineMode.java new file mode 100644 index 00000000..a6cfb7e1 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/rotor/mode/SineMode.java @@ -0,0 +1,59 @@ +package com.jverbruggen.jrides.animator.flatride.rotor.mode; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponentSpeed; +import com.jverbruggen.jrides.animator.flatride.rotor.axis.RotorAxis; +import org.bukkit.Bukkit; + +public class SineMode implements RotorActuatorMode { + private static final float PI = 3.1415926535f; + private static final float PI2 = PI*2; + + private final float size; + private final short phase; + private double sineState; + + public SineMode(float size, short phase) { + this.size = size; + this.phase = phase; + + resetToInitialPhase(); + } + + @Override + public void tick(FlatRideComponentSpeed flatRideComponentSpeed, RotorAxis rotorAxis) { + increaseSineState(flatRideComponentSpeed, rotorAxis); + } + + @Override + public double getLowerBound() { + return 0; + } + + @Override + public double getUpperBound() { + return PI2; + } + + private void resetToInitialPhase(){ + this.sineState = phase/180f*PI; + } + + private void increaseSineState(FlatRideComponentSpeed flatRideComponentSpeed, RotorAxis rotorAxis){ + sineState = (sineState + flatRideComponentSpeed.getSpeed()/180*PI) % PI2; + updateRotorAxis(rotorAxis, this.sineState); + } + + private void updateRotorAxis(RotorAxis rotorAxis, double sineState){ + rotorAxis.setRotation(Math.sin(sineState)*size); + } + + @Override + public double getRotation(RotorAxis rotorAxis) { + return sineState; + } + + @Override + public void setRotation(RotorAxis rotorAxis, double position) { + this.updateRotorAxis(rotorAxis, position); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/seat/FlatRideSeat.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/seat/FlatRideSeat.java new file mode 100644 index 00000000..2a2510ba --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/seat/FlatRideSeat.java @@ -0,0 +1,55 @@ +package com.jverbruggen.jrides.animator.flatride.seat; + +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.math.Vector3PlusYaw; +import com.jverbruggen.jrides.models.ride.flatride.PlayerControl; +import com.jverbruggen.jrides.models.ride.seat.AbstractSeat; +import com.jverbruggen.jrides.models.ride.seat.InstructionType; +import com.jverbruggen.jrides.models.ride.seat.SeatHost; + +public class FlatRideSeat extends AbstractSeat { + private PlayerControl playerControl; + + public FlatRideSeat(FlatRideHandle parentRideHandle, SeatHost seatHost, VirtualEntity virtualEntity, Vector3PlusYaw offset) { + super(parentRideHandle, seatHost, virtualEntity, offset); + this.playerControl = null; + + virtualEntity.setHostSeat(this); + setRestraint(parentRideHandle.getFirstTriggerContext().getRestraintTrigger().getLock().isUnlocked()); + } + + public void setPlayerControl(PlayerControl playerControl) { + this.playerControl = playerControl; + } + + @Override + public boolean supportsPlayerControl() { + return playerControl != null; + } + + @Override + public void sendPlayerControlInstruction(InstructionType instruction) { + if(playerControl == null) return; + + this.playerControl.processInstructionAsync(instruction); + } + + @Override + protected void onPassengerEnter(Player passenger) { + super.onPassengerEnter(passenger); + + if(playerControl != null) + playerControl.addControlling(passenger); + } + + @Override + protected void onPassengerExit(Player passenger) { + super.onPassengerExit(passenger); + + if(playerControl != null) + playerControl.removeControlling(passenger); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/seat/SeatComponent.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/seat/SeatComponent.java new file mode 100644 index 00000000..1b89ff35 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/seat/SeatComponent.java @@ -0,0 +1,90 @@ +package com.jverbruggen.jrides.animator.flatride.seat; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.animator.flatride.AbstractFlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.rotor.FlatRideModel; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.ride.coaster.train.Vehicle; +import com.jverbruggen.jrides.models.ride.factory.SeatFactory; +import com.jverbruggen.jrides.models.ride.seat.Seat; +import com.jverbruggen.jrides.models.ride.seat.SeatHost; + +import java.util.List; + +public class SeatComponent extends AbstractFlatRideComponent implements SeatHost { + private final Seat seat; + private final Quaternion rotationOffset; + private final Vehicle parentVehicle; + + public SeatComponent(String identifier, String groupIdentifier, boolean root, List flatRideModels, Seat seat, Quaternion rotationOffset, Vehicle parentVehicle) { + super(identifier, groupIdentifier, root, flatRideModels); + this.seat = seat; + this.rotationOffset = rotationOffset; + this.parentVehicle = parentVehicle; + } + + @Override + public void tick() { + super.tick(); + + SeatFactory.moveFlatRideSeat(this.seat, getPositionMatrix(), getRotation()); + } + + @Override + public Quaternion getRotation() { + return Quaternion.multiply(super.getRotation(), rotationOffset); + } + + @Override + public List getSeats() { + return List.of(seat); + } + + @Override + public List getPassengers() { + return List.of(seat.getPassenger()); + } + + @Override + public void ejectPassengers() { + if(seat.hasPassenger()) + seat.setPassenger(null); + } + + @Override + public void despawn() { + + } + + @Override + public void setRestraint(boolean locked) { + seat.setRestraint(locked); + } + + @Override + public boolean getRestraintState() { + return seat.restraintsActive(); + } + + @Override + public PlayerLocation getEjectLocation() { + return seat.getParentRideHandle().getEjectLocation(); + } + + @Override + public RideHandle getRideHandle() { + return seat.getParentRideHandle(); + } + + @Override + public void onPlayerEnter(Player player) { + parentVehicle.onPlayerEnter(player); + } + + @Override + public void onPlayerExit(Player player) { + parentVehicle.onPlayerExit(player); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/station/FlatRideStationHandle.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/station/FlatRideStationHandle.java new file mode 100644 index 00000000..029bb537 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/station/FlatRideStationHandle.java @@ -0,0 +1,37 @@ +package com.jverbruggen.jrides.animator.flatride.station; + +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.effect.handle.train.TrainEffectTriggerHandle; +import com.jverbruggen.jrides.models.properties.MinMaxWaitingTimer; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.ride.StationHandle; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.coaster.train.Vehicle; +import com.jverbruggen.jrides.models.ride.gate.Gate; + +import java.util.List; + +public class FlatRideStationHandle extends StationHandle { + private final FlatRideUniVehicle vehicle; + + public FlatRideStationHandle(String name, String shortName, List entryGates, PlayerLocation ejectLocation, MinMaxWaitingTimer waitingTimer, TriggerContext triggerContext, List entryBlockingEffectTriggers, List exitBlockingEffectTriggers, List exitEffectTriggers) { + super(name, shortName, entryGates, ejectLocation, waitingTimer, triggerContext, entryBlockingEffectTriggers, exitBlockingEffectTriggers, exitEffectTriggers); + this.vehicle = new FlatRideUniVehicle(name + "_vehicle", false, + triggerContext.getRestraintTrigger().getLock(), triggerContext.getVehiclePresentLock()); + } + + @Override + public Vehicle getStationaryVehicle() { + if(vehicle.isStationary()) return vehicle; + return null; + } + + public FlatRideUniVehicle getVehicle() { + return vehicle; + } + + public void setFlatRideHandle(FlatRideHandle flatRideHandle) { + this.vehicle.setFlatRideHandle(flatRideHandle); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/station/FlatRideUniVehicle.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/station/FlatRideUniVehicle.java new file mode 100644 index 00000000..d60f6137 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/station/FlatRideUniVehicle.java @@ -0,0 +1,92 @@ +package com.jverbruggen.jrides.animator.flatride.station; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.control.DispatchLock; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.ride.coaster.train.AbstractVehicle; + +import java.util.ArrayList; +import java.util.List; + +public class FlatRideUniVehicle extends AbstractVehicle { + private final List rootComponents; + private FlatRideHandle flatRideHandle; + private boolean onStation; + private final DispatchLock restraintLock; + + public FlatRideUniVehicle(String name, boolean debugMode, DispatchLock restraintLock, DispatchLock vehiclePresentLock) { + super(name, debugMode); + this.rootComponents = new ArrayList<>(); + this.onStation = true; + this.restraintLock = restraintLock; + + vehiclePresentLock.addEventListener(l -> setStationary(l.isUnlocked())); + } + + public void tick(){ + this.rootComponents.forEach(FlatRideComponent::tick); + } + + + public void addRootComponent(FlatRideComponent component){ + rootComponents.add(component); + } + + public List getRootComponents() { + return rootComponents; + } + + @Override + public boolean isStationary() { + return onStation; + } + + public void setStationary(boolean stationary){ + onStation = stationary; + } + + @Override + public boolean getRestraintState() { + return restraintLock.isUnlocked(); + } + + @Override + public void setRestraintForAll(boolean closed) { + restraintLock.setLocked(!closed); + } + + @Override + public void ejectPassengers() { + PlayerLocation ejectLocation = flatRideHandle.getEjectLocation(); + for(Player passenger : new ArrayList<>(getPassengers())){ + passenger.teleport(ejectLocation, true); + } + } + + @Override + public void playRestraintOpenSound() { + + } + + @Override + public void playRestraintCloseSound() { + + } + + @Override + public void playDispatchSound() { + + } + + @Override + public Vector3 getCurrentLocation() { + return flatRideHandle.getRootComponents().get(0).getPosition(); + } + + public void setFlatRideHandle(FlatRideHandle flatRideHandle) { + this.flatRideHandle = flatRideHandle; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/TimingSequence.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/TimingSequence.java new file mode 100644 index 00000000..4592f916 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/TimingSequence.java @@ -0,0 +1,55 @@ +package com.jverbruggen.jrides.animator.flatride.timing; + +import com.jverbruggen.jrides.animator.flatride.timing.instruction.InstructionSequenceItem; + +import java.util.Iterator; +import java.util.List; + +public class TimingSequence { + private final List items; + + private Iterator itemIterator; + private InstructionSequenceItem current; + private int state; + + public TimingSequence(List items) { + this.items = items; + this.state = 0; + this.current = null; + } + + public void restart(){ + if(this.current != null) + return; + + this.state = 0; + this.itemIterator = items.iterator(); + loadNext(); + } + + private void loadNext(){ + if(!itemIterator.hasNext()) + this.current = null; + else + this.current = itemIterator.next(); + } + + public boolean tick(){ + if(current == null) return false; + + boolean finished = current.tick(state); + if(finished) { + current.cleanUp(); + loadNext(); + state = 0; + return this.current == null; + }else{ + state++; + return false; + } + } + + public boolean isIdle(){ + return this.current == null; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/AnimationInstruction.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/AnimationInstruction.java new file mode 100644 index 00000000..fceb93a4 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/AnimationInstruction.java @@ -0,0 +1,49 @@ +package com.jverbruggen.jrides.animator.flatride.timing.instruction; + +import com.jverbruggen.jrides.animator.flatride.BlenderExportPositionRecord; +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.interfaces.Component6DOFPosition; +import com.jverbruggen.jrides.state.ride.flatride.Animation; +import com.jverbruggen.jrides.state.ride.flatride.AnimationHandle; + +public class AnimationInstruction implements Instruction { + private final AnimationHandle animationHandle; + private int frameIndexState; + + public AnimationInstruction(AnimationHandle animationHandle) { + this.animationHandle = animationHandle; + this.frameIndexState = 0; + } + + @Override + public void applyTo(FlatRideComponent component) { + Animation animation = animationHandle.getAnimation(component.getIdentifier()); + if(animation.getFrames().size() <= frameIndexState) return; + + BlenderExportPositionRecord position = animation.getFrames().get(frameIndexState); + + ((Component6DOFPosition)component).setPositionRotation( + position.toMinecraftVector(), + position.toMinecraftQuaternion()); + } + + @Override + public boolean canHandle(FlatRideComponent component) { + return component instanceof Component6DOFPosition; + } + + @Override + public void tick() { + frameIndexState++; + } + + @Override + public void reset() { + frameIndexState = 0; + } + + @Override + public void cleanUp(FlatRideComponent component) { + + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/ControlInstruction.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/ControlInstruction.java new file mode 100644 index 00000000..ad20f070 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/ControlInstruction.java @@ -0,0 +1,41 @@ +package com.jverbruggen.jrides.animator.flatride.timing.instruction; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.interfaces.PlayerControllable; + +public class ControlInstruction implements Instruction { + private final boolean allowControl; + + public ControlInstruction(boolean allowControl) { + this.allowControl = allowControl; + } + + public void execute(PlayerControllable playerControllable){ + playerControllable.setAllowControl(this.allowControl); + } + + @Override + public void applyTo(FlatRideComponent component) { + execute((PlayerControllable) component); + } + + @Override + public boolean canHandle(FlatRideComponent component) { + return component instanceof PlayerControllable; + } + + @Override + public void tick() { + + } + + @Override + public void reset() { + + } + + @Override + public void cleanUp(FlatRideComponent component) { + + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/Instruction.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/Instruction.java new file mode 100644 index 00000000..089e3796 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/Instruction.java @@ -0,0 +1,11 @@ +package com.jverbruggen.jrides.animator.flatride.timing.instruction; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; + +public interface Instruction { + void applyTo(FlatRideComponent component); + boolean canHandle(FlatRideComponent component); + void tick(); + void reset(); + void cleanUp(FlatRideComponent component); +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/InstructionBinding.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/InstructionBinding.java new file mode 100644 index 00000000..f31e1754 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/InstructionBinding.java @@ -0,0 +1,30 @@ +package com.jverbruggen.jrides.animator.flatride.timing.instruction; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; + +import java.util.List; + +public class InstructionBinding implements TimingAction { + private final Instruction instruction; + private final List flatRideComponents; + + public InstructionBinding(Instruction instruction, List flatRideComponents) { + this.instruction = instruction; + this.flatRideComponents = flatRideComponents; + } + + public void tick(){ + for(FlatRideComponent flatRideComponent : flatRideComponents){ + instruction.applyTo(flatRideComponent); + } + instruction.tick(); + } + + @Override + public void cleanUp() { + for(FlatRideComponent flatRideComponent : flatRideComponents){ + instruction.cleanUp(flatRideComponent); + } + instruction.reset(); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/InstructionSequenceItem.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/InstructionSequenceItem.java new file mode 100644 index 00000000..0766424d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/InstructionSequenceItem.java @@ -0,0 +1,29 @@ +package com.jverbruggen.jrides.animator.flatride.timing.instruction; + +import java.util.List; + +public class InstructionSequenceItem { + private final int durationTicks; + private final List actions; + + public InstructionSequenceItem(int durationTicks, List actions) { + this.durationTicks = durationTicks; + this.actions = actions; + } + + public boolean tick(int state){ + if(state > durationTicks) return true; + + for(TimingAction action : actions){ + action.tick(); + } + + return false; + } + + public void cleanUp(){ + for(TimingAction action : actions){ + action.cleanUp(); + } + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/SpeedInstruction.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/SpeedInstruction.java new file mode 100644 index 00000000..251dbc70 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/SpeedInstruction.java @@ -0,0 +1,45 @@ +package com.jverbruggen.jrides.animator.flatride.timing.instruction; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideComponentSpeed; +import com.jverbruggen.jrides.animator.flatride.interfaces.HasSpeed; + +public class SpeedInstruction implements Instruction { + private final float acceleration; + private final float speed; + + public SpeedInstruction(float acceleration, float speed) { + this.acceleration = acceleration; + this.speed = speed; + } + + public void execute(HasSpeed hasSpeed){ + FlatRideComponentSpeed speedComponent = hasSpeed.getFlatRideComponentSpeed(); + speedComponent.accelerateTowards(this.acceleration, this.speed); + } + + @Override + public void applyTo(FlatRideComponent component) { + execute((HasSpeed) component); + } + + @Override + public boolean canHandle(FlatRideComponent component) { + return component instanceof HasSpeed; + } + + @Override + public void tick() { + + } + + @Override + public void reset() { + + } + + @Override + public void cleanUp(FlatRideComponent component) { + + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/TimingAction.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/TimingAction.java new file mode 100644 index 00000000..5b7f3403 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/TimingAction.java @@ -0,0 +1,6 @@ +package com.jverbruggen.jrides.animator.flatride.timing.instruction; + +public interface TimingAction { + void tick(); + void cleanUp(); +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/towards/TowardsPositionInstruction.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/towards/TowardsPositionInstruction.java new file mode 100644 index 00000000..e1835ba9 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/towards/TowardsPositionInstruction.java @@ -0,0 +1,106 @@ +package com.jverbruggen.jrides.animator.flatride.timing.instruction.towards; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideComponentSpeed; +import com.jverbruggen.jrides.animator.flatride.interfaces.HasPosition; +import com.jverbruggen.jrides.animator.flatride.timing.instruction.Instruction; +import com.jverbruggen.jrides.models.math.SpeedUtil; + +import java.util.HashMap; +import java.util.Map; + +public class TowardsPositionInstruction implements Instruction { + private final double accelerate; + private final double minSpeed; + private final double maxSpeed; + private final double towardsPosition; + private final Map states; + + public TowardsPositionInstruction(double accelerate, double minSpeed, double maxSpeed, double towardsPosition) { + this.accelerate = accelerate; + this.minSpeed = minSpeed; + this.maxSpeed = maxSpeed; + this.towardsPosition = towardsPosition; + this.states = new HashMap<>(); + } + + public void execute(HasPosition hasPosition){ + if(!states.containsKey(hasPosition)){ + TowardsPositionInstructionState state = new TowardsPositionInstructionState(); + states.put(hasPosition, state); + execute(hasPosition, state); + }else{ + execute(hasPosition, states.get(hasPosition)); + } + } + + public void execute(HasPosition hasPosition, TowardsPositionInstructionState state){ + if (state.getOriginalState() == null) { + state.setOriginalState(hasPosition.getInstructionPosition()); + state.setAcceleration(accelerate); + + double lowerOperatingRange = hasPosition.getLowerOperatingRange(); + double upperOperatingRange = hasPosition.getUpperOperatingRange(); + +// JRidesPlugin.getLogger().debug("l: " + lowerOperatingRange + ", x: " + state.getOriginalState() + ", t: " + towardsPosition + ", p: " + positiveFrom); + + if(!SpeedUtil.aboveInRange(lowerOperatingRange, state.getOriginalState(), towardsPosition, upperOperatingRange, true)){ + state.setAcceleration(-accelerate); +// JRidesPlugin.getLogger().debug("Flipped " + state.getAcceleration()); + } + } + + double acc = state.getAcceleration(); + double lowerPosition = acc >= 0 ? state.getOriginalState() : this.towardsPosition; + double upperPosition = acc >= 0 ? this.towardsPosition : state.getOriginalState(); + +// JRidesPlugin.getLogger().debug("" + lowerPosition + "," + upperPosition + "," + acc); + TowardsPositionInstruction.run( + hasPosition, + acc, + lowerPosition, + upperPosition, + 0d, + this.maxSpeed, + this.minSpeed); + } + + @Override + public void applyTo(FlatRideComponent component) { + execute((HasPosition) component); + } + + @Override + public boolean canHandle(FlatRideComponent component) { + return component instanceof HasPosition; + } + + @Override + public void tick() { + + } + + @Override + public void reset() { + states.values().forEach(s -> { + s.setAcceleration(accelerate); + s.setOriginalState(null); + } + ); + } + + @Override + public void cleanUp(FlatRideComponent component) { + ((HasPosition)component).setInstructionPosition(towardsPosition); + } + + public static void run(HasPosition hasPosition, double acceleration, double lowerPosition, double upperPosition, double margin, double maxSpeed, double minSpeed){ + FlatRideComponentSpeed componentSpeed = hasPosition.getFlatRideComponentSpeed(); + boolean positiveAcceleration = acceleration >= 0; + + double targetPosition = positiveAcceleration ? upperPosition : lowerPosition; + double fromPosition = positiveAcceleration ? lowerPosition : upperPosition; + + hasPosition.goTowards(targetPosition, fromPosition, acceleration, componentSpeed); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/towards/TowardsPositionInstructionState.java b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/towards/TowardsPositionInstructionState.java new file mode 100644 index 00000000..77acabf4 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/flatride/timing/instruction/towards/TowardsPositionInstructionState.java @@ -0,0 +1,27 @@ +package com.jverbruggen.jrides.animator.flatride.timing.instruction.towards; + +public class TowardsPositionInstructionState { + private Double originalState; + private double acceleration; + + public TowardsPositionInstructionState() { + this.originalState = null; + this.acceleration = 0d; + } + + public Double getOriginalState() { + return originalState; + } + + public void setOriginalState(Double originalState) { + this.originalState = originalState; + } + + public double getAcceleration() { + return acceleration; + } + + public void setAcceleration(double acceleration) { + this.acceleration = acceleration; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/smoothanimation/SmoothAnimation.java b/src/main/java/com/jverbruggen/jrides/animator/smoothanimation/SmoothAnimation.java new file mode 100644 index 00000000..d61509d3 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/smoothanimation/SmoothAnimation.java @@ -0,0 +1,10 @@ +package com.jverbruggen.jrides.animator.smoothanimation; + +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.math.Quaternion; + +public interface SmoothAnimation { + boolean isEnabled(Player player); + void clearRotation(Player player); + void setRotation(Player player, Quaternion orientation); +} diff --git a/src/main/java/com/jverbruggen/jrides/animator/smoothanimation/SmoothAnimationSupport.java b/src/main/java/com/jverbruggen/jrides/animator/smoothanimation/SmoothAnimationSupport.java new file mode 100644 index 00000000..2111b697 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/smoothanimation/SmoothAnimationSupport.java @@ -0,0 +1,6 @@ +package com.jverbruggen.jrides.animator.smoothanimation; + +public enum SmoothAnimationSupport{ + UNKNOWN, AVAILABLE, UNAVAILABLE +} + diff --git a/src/main/java/com/jverbruggen/jrides/animator/smoothanimation/SmoothCoastersSmoothAnimation.java b/src/main/java/com/jverbruggen/jrides/animator/smoothanimation/SmoothCoastersSmoothAnimation.java new file mode 100644 index 00000000..0c9710a4 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/animator/smoothanimation/SmoothCoastersSmoothAnimation.java @@ -0,0 +1,32 @@ +package com.jverbruggen.jrides.animator.smoothanimation; + +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.math.Quaternion; +import me.m56738.smoothcoasters.api.SmoothCoastersAPI; + +public class SmoothCoastersSmoothAnimation implements SmoothAnimation { + private final SmoothCoastersAPI api; + + public SmoothCoastersSmoothAnimation(SmoothCoastersAPI api) { + this.api = api; + } + + @Override + public boolean isEnabled(Player player) { + return api.isEnabled(player.getBukkitPlayer()); + } + + @Override + public void clearRotation(Player player) { + api.resetRotation(null, player.getBukkitPlayer()); + } + + @Override + public void setRotation(Player player, Quaternion orientation) { + float x = (float) orientation.getX(); + float y = (float) orientation.getY(); + float z = (float) orientation.getZ(); + float w = (float) orientation.getW(); + api.setRotation(null, player.getBukkitPlayer(), x, y, z, w, (byte)3); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/api/JRidesPlayer.java b/src/main/java/com/jverbruggen/jrides/api/JRidesPlayer.java new file mode 100644 index 00000000..e86ccf21 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/api/JRidesPlayer.java @@ -0,0 +1,13 @@ +package com.jverbruggen.jrides.api; + +import java.util.UUID; + +public interface JRidesPlayer { + org.bukkit.entity.Player getBukkitPlayer(); + String getName(); + String getIdentifier(); + UUID getUniqueId(); + boolean isSeated(); + + void sendTitle(String title, String subtitle, int stay); +} diff --git a/src/main/java/com/jverbruggen/jrides/api/JRidesPlayerLocation.java b/src/main/java/com/jverbruggen/jrides/api/JRidesPlayerLocation.java new file mode 100644 index 00000000..e4c6f7a5 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/api/JRidesPlayerLocation.java @@ -0,0 +1,9 @@ +package com.jverbruggen.jrides.api; + +public interface JRidesPlayerLocation { + double getX(); + double getY(); + double getZ(); + double getYaw(); + double getPitch(); +} diff --git a/src/main/java/com/jverbruggen/jrides/api/JRidesRide.java b/src/main/java/com/jverbruggen/jrides/api/JRidesRide.java new file mode 100644 index 00000000..ef131641 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/api/JRidesRide.java @@ -0,0 +1,6 @@ +package com.jverbruggen.jrides.api; + +public interface JRidesRide { + String getIdentifier(); + JRidesPlayerLocation getWarpLocation(); +} diff --git a/src/main/java/com/jverbruggen/jrides/api/PlayerAPI.java b/src/main/java/com/jverbruggen/jrides/api/PlayerAPI.java new file mode 100644 index 00000000..251f7983 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/api/PlayerAPI.java @@ -0,0 +1,32 @@ +package com.jverbruggen.jrides.api; + +import com.jverbruggen.jrides.common.MenuSessionManager; +import com.jverbruggen.jrides.models.menu.Menu; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.player.PlayerManager; +import com.jverbruggen.jrides.state.ride.menu.RideOverviewMenuFactory; +import org.bukkit.inventory.Inventory; + +public class PlayerAPI { + private final PlayerManager playerManager; + private final RideOverviewMenuFactory rideOverviewMenuFactory; + private final MenuSessionManager menuSessionManager; + + public PlayerAPI() { + playerManager = ServiceProvider.getSingleton(PlayerManager.class); + rideOverviewMenuFactory = ServiceProvider.getSingleton(RideOverviewMenuFactory.class); + menuSessionManager = ServiceProvider.getSingleton(MenuSessionManager.class); + } + + public JRidesPlayer getFromBukkitPlayer(org.bukkit.entity.Player bukkitPlayer){ + return playerManager.getPlayer(bukkitPlayer); + } + + public void displayRideOverviewMenu(JRidesPlayer player){ + Menu menu = rideOverviewMenuFactory.getRideOverviewMenu(); + Inventory inventory = menu.getInventoryFor(player); + + menuSessionManager.addOpenMenu(player, menu, inventory); + player.getBukkitPlayer().openInventory(inventory); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/api/RidesAPI.java b/src/main/java/com/jverbruggen/jrides/api/RidesAPI.java new file mode 100644 index 00000000..285afad9 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/api/RidesAPI.java @@ -0,0 +1,23 @@ +package com.jverbruggen.jrides.api; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.RideManager; + +import java.util.List; + +public class RidesAPI { + private final RideManager rideManager; + + public RidesAPI(){ + this.rideManager = ServiceProvider.getSingleton(RideManager.class); + } + + public List getRides(){ + return this.rideManager.getRideHandles(); + } + + public RideHandle getRide(String rideIdentifier){ + return this.rideManager.getRideHandle(rideIdentifier); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/command/BaseCommandExecutor.java b/src/main/java/com/jverbruggen/jrides/command/BaseCommandExecutor.java new file mode 100644 index 00000000..9ede9ff7 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/command/BaseCommandExecutor.java @@ -0,0 +1,120 @@ +package com.jverbruggen.jrides.command; + +import com.jverbruggen.jrides.command.context.CommandContext; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; +import com.jverbruggen.jrides.models.entity.MessageReceiver; +import com.jverbruggen.jrides.models.entity.agent.MessageAgentManager; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.player.PlayerManager; +import org.bukkit.command.Command; +import org.bukkit.command.CommandSender; + +import java.util.*; +import java.util.stream.Collectors; + +public abstract class BaseCommandExecutor implements JRidesCommandExecutor { + protected final LanguageFile languageFile; + protected final PlayerManager playerManager; + protected final MessageAgentManager messageAgentManager; + protected final Map subCommands; + protected final int depth; + + protected BaseCommandExecutor(int depth) { + this.depth = depth; + this.languageFile = ServiceProvider.getSingleton(LanguageFile.class); + this.playerManager = ServiceProvider.getSingleton(PlayerManager.class); + this.messageAgentManager = ServiceProvider.getSingleton(MessageAgentManager.class); + this.subCommands = new HashMap<>(); + } + + @Override + public boolean onCommand(CommandSender commandSender, Command command, String s, String[] args) { + if(getPermission() != null && !commandSender.hasPermission(getPermission()) && !canEveryoneRun()){ + languageFile.sendMessage(commandSender, LanguageFileField.ERROR_GENERAL_NO_PERMISSION_MESSAGE); + return true; + } + + return onCommand(messageAgentManager.getOrCreateMessageAgent(commandSender), command, s, args, new CommandContext()); + } + + @Override + public boolean onCommand(MessageAgent messageAgent, Command command, String s, String[] args, CommandContext commandContext){ + if(args.length == depth){ + languageFile.sendMultilineMessage(messageAgent, getHelpMessageForParent()); + return true; + } + + commandContext.add(MessageReceiver.class, messageAgent); + String subCommand = args[depth]; + return runSubCommand(messageAgent, command, s, args, subCommand, commandContext); + } + + protected boolean runSubCommand(MessageAgent commandSender, Command command, String s, String[] args, String subCommand, CommandContext commandContext){ + JRidesCommandExecutor firstCommand = findSubCommand(subCommand); + if(firstCommand != null) { + if(!commandSender.hasPermission(firstCommand.getPermission())){ + languageFile.sendMessage(commandSender, LanguageFileField.ERROR_GENERAL_NO_PERMISSION_MESSAGE); + return true; + } + + firstCommand.onCommand(commandSender, command, s, args, commandContext); + return true; + } + + languageFile.sendMessage(commandSender, LanguageFileField.ERROR_UNKNOWN_COMMAND_MESSAGE); + return false; + } + + protected T registerSubCommand(T commandExecutor){ + subCommands.put(commandExecutor.getCommand(), commandExecutor); + return commandExecutor; + } + + public List getCommandSuggestions(MessageAgent forAgent){ + return subCommands.entrySet().stream() + .filter(entry -> forAgent.hasPermission(entry.getValue().getPermission())) + .map(Map.Entry::getKey) + .collect(Collectors.toList()); + } + + protected JRidesCommandExecutor findSubCommand(String command){ + return subCommands.get(command); + } + + @Override + public List onTabComplete(CommandSender commandSender, Command command, String s, String[] strings) { + return onTabComplete(messageAgentManager.getOrCreateMessageAgent(commandSender), command, s, strings); + } + + @Override + public List onTabComplete(MessageAgent messageAgent, Command command, String s, String[] strings) { + if(!messageAgent.hasPermission(getPermission())) return Collections.emptyList(); + + if(strings.length <= depth+1){ + return getCommandSuggestions(messageAgent); + }else{ + JRidesCommandExecutor subCommand = findSubCommand(strings[depth]); + if(subCommand == null) return List.of(); + return subCommand.onTabComplete(messageAgent, command, s, strings); + } + } + + @Override + public String getHelpMessageForSelf() { + return subCommands.values().stream() + .map(JRidesCommandExecutor::getHelpMessageForParent) + .collect(Collectors.joining("\n")); + } + + @Override + public String getPermission() { + return Permissions.COMMAND_ELEVATED_BASE; + } + + public boolean canEveryoneRun(){ + return false; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/command/BlockSectionCommandExecutor.java b/src/main/java/com/jverbruggen/jrides/command/BlockSectionCommandExecutor.java new file mode 100644 index 00000000..84808421 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/command/BlockSectionCommandExecutor.java @@ -0,0 +1,113 @@ +package com.jverbruggen.jrides.command; + +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.command.context.CommandContext; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.language.FeedbackType; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.section.Section; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.RideManager; +import org.bukkit.ChatColor; +import org.bukkit.command.Command; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class BlockSectionCommandExecutor extends BaseCommandExecutor { + private final RideManager rideManager; + + protected BlockSectionCommandExecutor() { + super(1); + this.rideManager = ServiceProvider.getSingleton(RideManager.class); + } + + @Override + public String getHelpMessageForParent() { + return "/jrides " + getCommand() + " "; + } + + @Override + public boolean onCommand(MessageAgent messageAgent, Command command, String arg, String[] args, CommandContext context) { + if(!messageAgent.isPlayer()){ + languageFile.sendMessage(messageAgent, LanguageFileField.ERROR_PLAYER_COMMAND_ONLY_MESSAGE); + return true; + } + + if(args.length != 2){ + languageFile.sendMessage(messageAgent, getHelpMessageForSelf()); + return true; + } + + String identifier = args[1]; + if(identifier.equalsIgnoreCase("")){ + languageFile.sendMessage(messageAgent, getHelpMessageForSelf()); + return true; + } + + RideHandle rideHandle = ServiceProvider.getSingleton(RideManager.class).getRideHandle(identifier); + if(rideHandle == null){ + languageFile.sendMessage(messageAgent, "Ride '" + identifier + "' not found", FeedbackType.CONFLICT); + return true; + } + + if(!(rideHandle instanceof CoasterHandle)){ + languageFile.sendMessage(messageAgent, "Ride has no track", FeedbackType.CONFLICT); + return true; + } + + Track track = ((CoasterHandle)rideHandle).getTrack(); + if(track == null){ + languageFile.sendMessage(messageAgent, "Track was not found", FeedbackType.CONFLICT); + return true; + } + + List
sections = new ArrayList<>(track.getSections()); + Collections.sort(sections); + + languageFile.sendMessage(messageAgent, "-- Block section occupations --"); + for(Section section : sections){ + boolean occupied = section.isOccupied(); + boolean reserved = section.getReservedBy() != null; + boolean safe = section.getBlockSectionSafety(null).safe(); + + ChatColor color = ChatColor.GREEN; + if(occupied) color = ChatColor.RED; + else if(reserved) color = ChatColor.DARK_AQUA; + else if(!safe) color = ChatColor.YELLOW; + + languageFile.sendMessage(messageAgent, color + section.toString()); + } + + + return true; + } + + @Override + public String getHelpMessageForSelf() { + return getHelpMessageForParent(); + } + + @Override + public String getCommand() { + return "blocksections"; + } + + @Override + public String getPermission() { + return Permissions.COMMAND_ELEVATED_BLOCK_SECTION; + } + + @Override + public List onTabComplete(MessageAgent messageAgent, Command command, String s, String[] strings) { + if(!messageAgent.hasPermission(getPermission())) return Collections.emptyList(); + + if(strings.length == depth+1) + return rideManager.getRideIdentifiers(); + return null; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/command/HelpCommandExecutor.java b/src/main/java/com/jverbruggen/jrides/command/HelpCommandExecutor.java new file mode 100644 index 00000000..adf00f36 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/command/HelpCommandExecutor.java @@ -0,0 +1,30 @@ +package com.jverbruggen.jrides.command; + +import java.util.Objects; +import java.util.stream.Collectors; + +public class HelpCommandExecutor extends BaseCommandExecutor { + private final MainCommandExecutor mainCommandExecutor; + + public HelpCommandExecutor(MainCommandExecutor mainCommandExecutor) { + super(1); + this.mainCommandExecutor = mainCommandExecutor; + } + + @Override + public String getCommand() { + return "help"; + } + + @Override + public String getHelpMessageForParent() { + return mainCommandExecutor.subCommands.values().stream() + .map(executor -> { + if(executor == this) return null; + return executor.getHelpMessageForParent(); + }) + .filter(Objects::nonNull) + .sorted() + .collect(Collectors.joining("\n")); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/command/JRidesCommandExecutor.java b/src/main/java/com/jverbruggen/jrides/command/JRidesCommandExecutor.java new file mode 100644 index 00000000..b2c965ad --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/command/JRidesCommandExecutor.java @@ -0,0 +1,19 @@ +package com.jverbruggen.jrides.command; + +import com.jverbruggen.jrides.command.context.CommandContext; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.TabCompleter; + +import java.util.List; + +public interface JRidesCommandExecutor extends CommandExecutor, TabCompleter { + String getHelpMessageForParent(); + String getCommand(); + String getHelpMessageForSelf(); + boolean onCommand(MessageAgent messageAgent, Command command, String s, String[] args, CommandContext commandContext); + List onTabComplete(MessageAgent messageAgent, Command command, String s, String[] strings); + String getPermission(); + +} diff --git a/src/main/java/com/jverbruggen/jrides/command/MainCommandExecutor.java b/src/main/java/com/jverbruggen/jrides/command/MainCommandExecutor.java new file mode 100644 index 00000000..dc0dc5a9 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/command/MainCommandExecutor.java @@ -0,0 +1,39 @@ +package com.jverbruggen.jrides.command; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.command.control.ControlCommandExecutor; +import org.bukkit.ChatColor; + +public class MainCommandExecutor extends BaseCommandExecutor { + public MainCommandExecutor() { + super(0); + registerSubCommand(new HelpCommandExecutor(this)); + registerSubCommand(new BlockSectionCommandExecutor()); + registerSubCommand(new VisualizeCommandExecutor()); + registerSubCommand(new ControlCommandExecutor()); + registerSubCommand(new WarpCommandExecutor()); + registerSubCommand(new RideOverviewMapCommandExecutor()); + registerSubCommand(new RideCounterMapCommandExecutor()); + registerSubCommand(new RidesCommandExecutor()); + } + + @Override + public String getCommand() { + return null; + } + + @Override + public String getPermission() { + return null; + } + + @Override + public String getHelpMessageForParent() { + return ChatColor.GOLD + "This server is running jrides - " + JRidesPlugin.getVersion(); + } + + @Override + public boolean canEveryoneRun() { + return true; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/command/RideCounterMapCommandExecutor.java b/src/main/java/com/jverbruggen/jrides/command/RideCounterMapCommandExecutor.java new file mode 100644 index 00000000..8f9d9e27 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/command/RideCounterMapCommandExecutor.java @@ -0,0 +1,98 @@ +package com.jverbruggen.jrides.command; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.command.context.CommandContext; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.language.FeedbackType; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; +import com.jverbruggen.jrides.models.map.ridecounter.RideCounterMapFactory; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.RideManager; +import org.bukkit.command.Command; + +import java.util.Collections; +import java.util.List; + +public class RideCounterMapCommandExecutor extends BaseCommandExecutor { + private final RideManager rideManager; + private final RideCounterMapFactory rideCounterMapFactory; + + protected RideCounterMapCommandExecutor() { + super(1); + this.rideManager = ServiceProvider.getSingleton(RideManager.class); + this.rideCounterMapFactory = ServiceProvider.getSingleton(RideCounterMapFactory.class); + } + + @Override + public String getHelpMessageForParent() { + return "/jrides " + getCommand() + " "; + } + + @Override + public boolean onCommand(MessageAgent messageAgent, Command command, String arg, String[] args, CommandContext context) { + if(!messageAgent.isPlayer()){ + languageFile.sendMessage(messageAgent, LanguageFileField.ERROR_PLAYER_COMMAND_ONLY_MESSAGE); + return true; + } + + if(args.length != 3){ + languageFile.sendMessage(messageAgent, getHelpMessageForSelf()); + return true; + } + + String rideIdentifier = args[1]; + if(rideIdentifier.equalsIgnoreCase("")){ + languageFile.sendMessage(messageAgent, getHelpMessageForSelf()); + return true; + } + + String boardIdentifier = args[2]; + if(boardIdentifier.equalsIgnoreCase("")){ + languageFile.sendMessage(messageAgent, getHelpMessageForSelf()); + return true; + } + + RideHandle rideHandle = ServiceProvider.getSingleton(RideManager.class).getRideHandle(rideIdentifier); + if(rideHandle == null){ + languageFile.sendMessage(messageAgent, "Ride '" + rideIdentifier + "' not found", FeedbackType.CONFLICT); + return true; + } + + Player player = messageAgent.getPlayer(playerManager); + rideCounterMapFactory.giveMap(player, rideHandle, boardIdentifier); + + return true; + } + + @Override + public String getHelpMessageForSelf() { + return getHelpMessageForParent(); + } + + @Override + public String getCommand() { + return "ridecountermap"; + } + + @Override + public String getPermission() { + return Permissions.COMMAND_ELEVATED_RIDE_COUNTER_MAP; + } + + @Override + public List onTabComplete(MessageAgent messageAgent, Command command, String s, String[] strings) { + if(!messageAgent.hasPermission(getPermission())) return Collections.emptyList(); + + if(strings.length == depth+1) + return rideManager.getRideIdentifiers(); + + if(strings.length == depth+2) + return rideCounterMapFactory.getBoardIdentifiersByRide(strings[depth+1]); + + return null; + } + + +} diff --git a/src/main/java/com/jverbruggen/jrides/command/RideOverviewMapCommandExecutor.java b/src/main/java/com/jverbruggen/jrides/command/RideOverviewMapCommandExecutor.java new file mode 100644 index 00000000..4132f441 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/command/RideOverviewMapCommandExecutor.java @@ -0,0 +1,92 @@ +package com.jverbruggen.jrides.command; + +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.command.context.CommandContext; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.language.FeedbackType; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; +import com.jverbruggen.jrides.models.map.rideoverview.RideOverviewMapFactory; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.RideManager; +import org.bukkit.command.Command; + +import java.util.Collections; +import java.util.List; + +public class RideOverviewMapCommandExecutor extends BaseCommandExecutor { + private final RideManager rideManager; + private final RideOverviewMapFactory rideOverviewMapFactory; + + protected RideOverviewMapCommandExecutor() { + super(1); + this.rideManager = ServiceProvider.getSingleton(RideManager.class); + this.rideOverviewMapFactory = ServiceProvider.getSingleton(RideOverviewMapFactory.class); + } + + @Override + public String getHelpMessageForParent() { + return "/jrides " + getCommand() + " "; + } + + @Override + public boolean onCommand(MessageAgent messageAgent, Command command, String arg, String[] args, CommandContext context) { + if(!messageAgent.isPlayer()){ + languageFile.sendMessage(messageAgent, LanguageFileField.ERROR_PLAYER_COMMAND_ONLY_MESSAGE); + return true; + } + + if(args.length != 2){ + languageFile.sendMessage(messageAgent, getHelpMessageForSelf()); + return true; + } + + String identifier = args[1]; + if(identifier.equalsIgnoreCase("")){ + languageFile.sendMessage(messageAgent, getHelpMessageForSelf()); + return true; + } + + RideHandle rideHandle = ServiceProvider.getSingleton(RideManager.class).getRideHandle(identifier); + if(rideHandle == null){ + languageFile.sendMessage(messageAgent, "Ride '" + identifier + "' not found", FeedbackType.CONFLICT); + return true; + } + + if(!(rideHandle instanceof CoasterHandle)){ + languageFile.sendMessage(messageAgent, "Ride has no track", FeedbackType.CONFLICT); + return true; + } + + Player player = messageAgent.getPlayer(playerManager); + rideOverviewMapFactory.giveMap(player, ((CoasterHandle) rideHandle)); + + return true; + } + + @Override + public String getHelpMessageForSelf() { + return getHelpMessageForParent(); + } + + @Override + public String getCommand() { + return "rideoverview"; + } + + @Override + public String getPermission() { + return Permissions.COMMAND_ELEVATED_RIDE_OVERVIEW; + } + + @Override + public List onTabComplete(MessageAgent messageAgent, Command command, String s, String[] strings) { + if(!messageAgent.hasPermission(getPermission())) return Collections.emptyList(); + + if(strings.length == depth+1) + return rideManager.getRideIdentifiers(); + return null; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/command/RidesCommandExecutor.java b/src/main/java/com/jverbruggen/jrides/command/RidesCommandExecutor.java new file mode 100644 index 00000000..527f96b8 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/command/RidesCommandExecutor.java @@ -0,0 +1,76 @@ +package com.jverbruggen.jrides.command; + +import com.jverbruggen.jrides.command.context.CommandContext; +import com.jverbruggen.jrides.common.MenuSessionManager; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; +import com.jverbruggen.jrides.models.menu.Menu; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.menu.RideOverviewMenuFactory; +import org.bukkit.command.Command; +import org.bukkit.inventory.Inventory; + +import java.util.Collections; +import java.util.List; + +public class RidesCommandExecutor extends BaseCommandExecutor { + private final RideOverviewMenuFactory rideOverviewMenuFactory; + private final MenuSessionManager menuSessionManager; + + protected RidesCommandExecutor() { + super(1); + this.rideOverviewMenuFactory = ServiceProvider.getSingleton(RideOverviewMenuFactory.class); + this.menuSessionManager = ServiceProvider.getSingleton(MenuSessionManager.class); + } + + @Override + public String getHelpMessageForParent() { + return "/jrides " + getCommand(); + } + + @Override + public boolean onCommand(MessageAgent messageAgent, Command command, String arg, String[] args, CommandContext context) { + if(!messageAgent.isPlayer()){ + languageFile.sendMessage(messageAgent, LanguageFileField.ERROR_PLAYER_COMMAND_ONLY_MESSAGE); + return true; + } + + if(args.length != 1){ + languageFile.sendMessage(messageAgent, getHelpMessageForSelf()); + return true; + } + + Player player = messageAgent.getPlayer(playerManager); + + Menu menu = rideOverviewMenuFactory.getRideOverviewMenu(); + Inventory inventory = menu.getInventoryFor(player); + menuSessionManager.addOpenMenu(player, menu, inventory); + player.getBukkitPlayer().openInventory(inventory); + + return true; + } + + @Override + public String getHelpMessageForSelf() { + return getHelpMessageForParent(); + } + + @Override + public String getCommand() { + return "rides"; + } + + @Override + public String getPermission() { + return Permissions.COMMAND_RIDES_MENU; + } + + @Override + public List onTabComplete(MessageAgent messageAgent, Command command, String s, String[] strings) { + if(!messageAgent.hasPermission(getPermission())) return Collections.emptyList(); + + return null; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/command/VisualizeCommandExecutor.java b/src/main/java/com/jverbruggen/jrides/command/VisualizeCommandExecutor.java new file mode 100644 index 00000000..d32292f8 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/command/VisualizeCommandExecutor.java @@ -0,0 +1,108 @@ +package com.jverbruggen.jrides.command; + +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.animator.coaster.tool.ParticleTrackVisualisationTool; +import com.jverbruggen.jrides.command.context.CommandContext; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.language.FeedbackType; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.language.LanguageFileTag; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.RideManager; +import org.bukkit.command.Command; + +import java.util.Collections; +import java.util.List; + +public class VisualizeCommandExecutor extends BaseCommandExecutor { + private final RideManager rideManager; + + protected VisualizeCommandExecutor() { + super(1); + this.rideManager = ServiceProvider.getSingleton(RideManager.class); + } + + @Override + public String getHelpMessageForParent() { + return "/jrides visualize "; + } + + @Override + public boolean onCommand(MessageAgent messageAgent, Command command, String arg, String[] args, CommandContext context) { + if(!messageAgent.isPlayer()){ + languageFile.sendMessage(messageAgent, LanguageFileField.ERROR_PLAYER_COMMAND_ONLY_MESSAGE); + return true; + } + + if(args.length != 2){ + languageFile.sendMessage(messageAgent, getHelpMessageForSelf()); + return true; + } + + String identifier = args[1]; + if(identifier.equalsIgnoreCase("")){ + languageFile.sendMessage(messageAgent, getHelpMessageForSelf()); + return true; + } + + RideHandle rideHandle = ServiceProvider.getSingleton(RideManager.class).getRideHandle(identifier); + if(rideHandle == null){ + languageFile.sendMessage(messageAgent, "Ride '" + identifier + "' not found", FeedbackType.CONFLICT); + return true; + } + + if(!(rideHandle instanceof CoasterHandle coasterHandle)){ + languageFile.sendMessage(messageAgent, "Ride cannot be visualized: not a coaster", FeedbackType.CONFLICT); + return true; + } + + ParticleTrackVisualisationTool tool = coasterHandle.getVisualisationTool(); + if(tool == null){ + languageFile.sendMessage(messageAgent, "Could not visualize track", FeedbackType.CONFLICT); + return true; + } + + String actualIdentifier = coasterHandle.getRide().getIdentifier(); + Player player = messageAgent.getPlayer(playerManager); + if(tool.isViewer(player)){ + tool.removeViewer(player); + + languageFile.sendMessage(player, LanguageFileField.COMMAND_VISUALIZE_REMOVED_VIEWER, + b -> b.add(LanguageFileTag.rideIdentifier, actualIdentifier)); + }else{ + tool.addViewer(player); + + languageFile.sendMessage(player, LanguageFileField.COMMAND_VISUALIZE_ADDED_VIEWER, + b -> b.add(LanguageFileTag.rideIdentifier, actualIdentifier)); + } + + return true; + } + + @Override + public String getHelpMessageForSelf() { + return getHelpMessageForParent(); + } + + @Override + public String getCommand() { + return "visualize"; + } + + @Override + public String getPermission() { + return Permissions.COMMAND_ELEVATED_VISUALIZE; + } + + @Override + public List onTabComplete(MessageAgent messageAgent, Command command, String s, String[] strings) { + if(!messageAgent.hasPermission(getPermission())) return Collections.emptyList(); + + if(strings.length == depth+1) + return rideManager.getRideIdentifiers(); + return null; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/command/WarpCommandExecutor.java b/src/main/java/com/jverbruggen/jrides/command/WarpCommandExecutor.java new file mode 100644 index 00000000..c9a1cc56 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/command/WarpCommandExecutor.java @@ -0,0 +1,87 @@ +package com.jverbruggen.jrides.command; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.command.context.CommandContext; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.event.player.PlayerTeleportByJRidesEvent; +import com.jverbruggen.jrides.language.FeedbackType; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.language.LanguageFileTag; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.RideManager; +import org.bukkit.command.Command; + +import java.util.Collections; +import java.util.List; + +public class WarpCommandExecutor extends BaseCommandExecutor { + private final RideManager rideManager; + + protected WarpCommandExecutor() { + super(1); + this.rideManager = ServiceProvider.getSingleton(RideManager.class); + } + + @Override + public String getHelpMessageForParent() { + return "/jrides warp "; + } + + @Override + public boolean onCommand(MessageAgent messageAgent, Command command, String arg, String[] args, CommandContext context) { + if(!messageAgent.isPlayer()){ + languageFile.sendMessage(messageAgent, LanguageFileField.ERROR_PLAYER_COMMAND_ONLY_MESSAGE); + return true; + } + + if(args.length != 2){ + languageFile.sendMessage(messageAgent, getHelpMessageForSelf()); + return true; + } + + String identifier = args[1]; + + Player player = messageAgent.getPlayer(playerManager); + if(!player.getBukkitPlayer().hasPermission(Permissions.COMMAND_RIDE_WARP)){ + languageFile.sendMessage(player, LanguageFileField.ERROR_GENERAL_NO_PERMISSION_MESSAGE); + return false; + } + + RideHandle rideHandle = ServiceProvider.getSingleton(RideManager.class).getRideHandle(identifier); + if(rideHandle == null){ + languageFile.sendMessage(messageAgent, "Ride '" + identifier + "' not found", FeedbackType.CONFLICT); + return true; + } + PlayerTeleportByJRidesEvent.sendEvent(player, rideHandle.getRide().getWarpLocation(), false); + + player.teleport(rideHandle.getRide().getWarpLocation()); + languageFile.sendMessage(player, LanguageFileField.NOTIFICATION_WARPED, b -> b.add(LanguageFileTag.rideDisplayName, rideHandle.getRide().getDisplayName())); + return true; + } + + @Override + public String getHelpMessageForSelf() { + return getHelpMessageForParent(); + } + + @Override + public String getCommand() { + return "warp"; + } + + @Override + public String getPermission() { + return Permissions.COMMAND_RIDE_WARP; + } + + @Override + public List onTabComplete(MessageAgent messageAgent, Command command, String s, String[] strings) { + if(!messageAgent.hasPermission(getPermission())) return Collections.emptyList(); + + if(strings.length == depth+1) + return rideManager.getRideIdentifiers(); + return null; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/command/context/CommandContext.java b/src/main/java/com/jverbruggen/jrides/command/context/CommandContext.java new file mode 100644 index 00000000..3b50aa52 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/command/context/CommandContext.java @@ -0,0 +1,24 @@ +package com.jverbruggen.jrides.command.context; + +import java.util.HashMap; +import java.util.Map; + +@SuppressWarnings("rawtypes") +public class CommandContext { + private final Map objects; + + public CommandContext() { + this.objects = new HashMap<>(); + } + + public CommandContext add(Class clazz, Object object){ + objects.put(clazz, object); + return this; + } + + public T get(Class clazz){ + Object object = objects.get(clazz); + if(!clazz.isInstance(object)) throw new RuntimeException("Non-matching type in command context for type " + clazz.getTypeName()); + return clazz.cast(object); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/command/control/ControlAdminMenuCommandExecutor.java b/src/main/java/com/jverbruggen/jrides/command/control/ControlAdminMenuCommandExecutor.java new file mode 100644 index 00000000..68621064 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/command/control/ControlAdminMenuCommandExecutor.java @@ -0,0 +1,64 @@ +package com.jverbruggen.jrides.command.control; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.command.BaseCommandExecutor; +import com.jverbruggen.jrides.command.context.CommandContext; +import com.jverbruggen.jrides.common.MenuSessionManager; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.control.uiinterface.menu.RideControlMenuFactory; +import com.jverbruggen.jrides.language.FeedbackType; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; +import com.jverbruggen.jrides.models.menu.Menu; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.command.Command; +import org.bukkit.inventory.Inventory; + +public class ControlAdminMenuCommandExecutor extends BaseCommandExecutor { + private final RideControlMenuFactory rideControlMenuFactory; + private final MenuSessionManager menuSessionManager; + + protected ControlAdminMenuCommandExecutor(int depth) { + super(depth); + this.rideControlMenuFactory = ServiceProvider.getSingleton(RideControlMenuFactory.class); + this.menuSessionManager = ServiceProvider.getSingleton(MenuSessionManager.class); + } + + @Override + public boolean onCommand(MessageAgent messageAgent, Command command, String s, String[] args, CommandContext commandContext) { + if(!messageAgent.isPlayer()){ + languageFile.sendMessage(messageAgent, LanguageFileField.ERROR_PLAYER_COMMAND_ONLY_MESSAGE, FeedbackType.CONFLICT); + return true; + } + + Player player = messageAgent.getPlayer(playerManager); + + RideHandle rideHandle = commandContext.get(RideHandle.class); + Menu rideControlMenu = rideControlMenuFactory.getAdminMenu(rideHandle.getRideController()); + if(rideControlMenu == null){ + languageFile.sendMessage(player, LanguageFileField.ERROR_RIDE_CONTROL_MENU_NOT_FOUND, FeedbackType.CONFLICT); + return true; + } + Inventory inventory = rideControlMenu.getInventoryFor(player); + + menuSessionManager.addOpenMenu(player, rideControlMenu, inventory); + player.getBukkitPlayer().openInventory(inventory); + return true; + } + + @Override + public String getCommand() { + return "admin"; + } + + @Override + public String getPermission() { + return Permissions.COMMAND_ELEVATED_ADMIN_MENU; + } + + @Override + public String getHelpMessageForParent() { + return "/jrides control admin"; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/command/control/ControlCommandExecutor.java b/src/main/java/com/jverbruggen/jrides/command/control/ControlCommandExecutor.java new file mode 100644 index 00000000..f497ddba --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/command/control/ControlCommandExecutor.java @@ -0,0 +1,76 @@ +package com.jverbruggen.jrides.command.control; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.command.BaseCommandExecutor; +import com.jverbruggen.jrides.command.context.CommandContext; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.language.FeedbackType; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.RideManager; +import org.bukkit.command.Command; + +import java.util.Collections; +import java.util.List; + +public class ControlCommandExecutor extends BaseCommandExecutor { + private final RideManager rideManager; + + public ControlCommandExecutor() { + super(1); + rideManager = ServiceProvider.getSingleton(RideManager.class); + + registerSubCommand(new ControlMenuCommandExecutor(depth+2)); + registerSubCommand(new ControlAdminMenuCommandExecutor(depth+2)); + registerSubCommand(new ControlDispatchCommandExecutor(depth+2)); + } + + @Override + public boolean onCommand(MessageAgent messageAgent, Command command, String arg, String[] args, CommandContext commandContext) { + if(args.length <= 2){ + languageFile.sendMultilineMessage(messageAgent, getHelpMessageForSelf()); + return true; + } + + String identifier = args[1]; + String subCommand = args[2]; + + RideHandle rideHandle = rideManager.getRideHandle(identifier); + if(rideHandle == null){ + languageFile.sendMessage(messageAgent, "Ride '" + identifier + "' not found", FeedbackType.CONFLICT); + return true; + } + + commandContext.add(RideHandle.class, rideHandle); + + runSubCommand(messageAgent, command, arg, args, subCommand, commandContext); + return true; + } + + @Override + public String getCommand() { + return "control"; + } + + @Override + public String getPermission() { + return Permissions.COMMAND_CONTROL; + } + + @Override + public String getHelpMessageForParent() { + return "/jrides control"; + } + + @Override + public List onTabComplete(MessageAgent messageAgent, Command command, String s, String[] strings) { + if(!messageAgent.hasPermission(getPermission())) return Collections.emptyList(); + + if(strings.length == depth+1){ + return rideManager.getRideIdentifiers(); + }else if(strings.length == depth+2){ + return getCommandSuggestions(messageAgent); + } + return null; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/command/control/ControlDispatchCommandExecutor.java b/src/main/java/com/jverbruggen/jrides/command/control/ControlDispatchCommandExecutor.java new file mode 100644 index 00000000..d3ba21aa --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/command/control/ControlDispatchCommandExecutor.java @@ -0,0 +1,53 @@ +package com.jverbruggen.jrides.command.control; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.command.BaseCommandExecutor; +import com.jverbruggen.jrides.command.context.CommandContext; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.control.controller.RideController; +import com.jverbruggen.jrides.control.trigger.SimpleDispatchTrigger; +import com.jverbruggen.jrides.language.FeedbackType; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.language.LanguageFileTag; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; +import org.bukkit.command.Command; + +public class ControlDispatchCommandExecutor extends BaseCommandExecutor { + protected ControlDispatchCommandExecutor(int depth) { + super(depth); + } + + @Override + public boolean onCommand(MessageAgent messageAgent, Command command, String s, String[] args, CommandContext commandContext) { + RideHandle rideHandle = commandContext.get(RideHandle.class); + RideController rideController = rideHandle.getRideController(); + if(rideController == null){ + languageFile.sendMessage(messageAgent, LanguageFileField.ERROR_RIDE_CONTROL_MENU_NOT_FOUND, FeedbackType.CONFLICT); + return true; + } + + SimpleDispatchTrigger dispatchTrigger = rideController.getTriggerContext().getDispatchTrigger(); + + boolean dispatched = dispatchTrigger.execute(messageAgent); + if(dispatched) + languageFile.sendMessage(messageAgent, LanguageFileField.COMMAND_RIDE_DISPATCHED_MESSAGE, + b -> b.add(LanguageFileTag.rideDisplayName, rideHandle.getRide().getDisplayName())); + + return true; + } + + @Override + public String getCommand() { + return "dispatch"; + } + + @Override + public String getPermission() { + return Permissions.COMMAND_CONTROL_DISPATCH; + } + + @Override + public String getHelpMessageForParent() { + return "/jrides control dispatch"; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/command/control/ControlMenuCommandExecutor.java b/src/main/java/com/jverbruggen/jrides/command/control/ControlMenuCommandExecutor.java new file mode 100644 index 00000000..cba0f27b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/command/control/ControlMenuCommandExecutor.java @@ -0,0 +1,61 @@ +package com.jverbruggen.jrides.command.control; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.command.BaseCommandExecutor; +import com.jverbruggen.jrides.command.context.CommandContext; +import com.jverbruggen.jrides.common.MenuSessionManager; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.language.FeedbackType; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; +import com.jverbruggen.jrides.models.menu.Menu; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.command.Command; +import org.bukkit.inventory.Inventory; + +public class ControlMenuCommandExecutor extends BaseCommandExecutor { + private final MenuSessionManager menuSessionManager; + + protected ControlMenuCommandExecutor(int depth) { + super(depth); + this.menuSessionManager = ServiceProvider.getSingleton(MenuSessionManager.class); + } + + @Override + public boolean onCommand(MessageAgent messageAgent, Command command, String s, String[] args, CommandContext commandContext) { + if(!messageAgent.isPlayer()){ + languageFile.sendMessage(messageAgent, LanguageFileField.ERROR_PLAYER_COMMAND_ONLY_MESSAGE, FeedbackType.CONFLICT); + return true; + } + + Player player = messageAgent.getPlayer(playerManager); + + RideHandle rideHandle = commandContext.get(RideHandle.class); + Menu rideControlMenu = rideHandle.getRideControlMenu(); + if(rideControlMenu == null){ + languageFile.sendMessage(messageAgent, LanguageFileField.ERROR_RIDE_CONTROL_MENU_NOT_FOUND, FeedbackType.CONFLICT); + return true; + } + Inventory inventory = rideControlMenu.getInventoryFor(player); + + menuSessionManager.addOpenMenu(player, rideControlMenu, inventory); + player.getBukkitPlayer().openInventory(inventory); + return true; + } + + @Override + public String getCommand() { + return "menu"; + } + + @Override + public String getPermission() { + return Permissions.COMMAND_CONTROL_MENU; + } + + @Override + public String getHelpMessageForParent() { + return "/jrides control menu"; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/common/MenuSessionManager.java b/src/main/java/com/jverbruggen/jrides/common/MenuSessionManager.java new file mode 100644 index 00000000..c95e428a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/common/MenuSessionManager.java @@ -0,0 +1,48 @@ +package com.jverbruggen.jrides.common; + +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.models.menu.Menu; +import org.bukkit.entity.Player; +import org.bukkit.inventory.Inventory; + +import java.util.HashMap; +import java.util.Map; + +public class MenuSessionManager { + private final Map openMenus; + + public MenuSessionManager(){ + this.openMenus = new HashMap<>(); + } + + public void addOpenMenu(JRidesPlayer player, Menu menu, Inventory inventory){ + menu.addSession(player, inventory); + openMenus.put(player, menu); + menu.sendUpdate(); + } + + public Menu getOpenMenu(JRidesPlayer player){ + return openMenus.get(player); + } + + public void removeOpenMenu(JRidesPlayer player){ + Menu menu = openMenus.get(player); + if(menu == null) return; + + menu.removeSession(player); + openMenus.remove(player); + } + + public boolean hasOpenMenu(JRidesPlayer player){ + return openMenus.containsKey(player); + } + + public void closeAllOpenMenus(){ + for(Map.Entry entry : openMenus.entrySet()){ + JRidesPlayer player = entry.getKey(); + Player bukkitPlayer = player.getBukkitPlayer(); + bukkitPlayer.closeInventory(); + removeOpenMenu(player); + } + } +} diff --git a/src/main/java/com/jverbruggen/jrides/common/Reason.java b/src/main/java/com/jverbruggen/jrides/common/Reason.java new file mode 100644 index 00000000..6d4d83d5 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/common/Reason.java @@ -0,0 +1,21 @@ +package com.jverbruggen.jrides.common; + +import com.jverbruggen.jrides.language.FeedbackType; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; + +public record Reason(String description, FeedbackType feedbackType) { + public void sendAsMessage(MessageAgent messageAgent){ + LanguageFile languageFile = ServiceProvider.getSingleton(LanguageFile.class); + languageFile.sendMessage(messageAgent, description); + } + + public static Reason simple(String description){ + return new Reason(description, FeedbackType.INFO); + } + + public static Reason conflict(String description){ + return new Reason(description, FeedbackType.CONFLICT); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/common/Result.java b/src/main/java/com/jverbruggen/jrides/common/Result.java new file mode 100644 index 00000000..513449d5 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/common/Result.java @@ -0,0 +1,47 @@ +package com.jverbruggen.jrides.common; + +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; + +import java.util.ArrayList; +import java.util.List; + +public record Result(boolean ok, List reasons) { + public void sendMessageTo(MessageAgent messageAgent){ + for(Reason reason : reasons){ + reason.sendAsMessage(messageAgent); + } + } + + public void concat(Result other){ + reasons.addAll(other.reasons); + } + + public static Result isOk(){ + return new Result(true, new ArrayList<>()); + } + + public static Result isNotOk() { + return new Result(false, new ArrayList<>()); + } + + public static Result isNotOk(String title){ + return isNotOk(title, List.of()); + } + + public static Result isNotOk(List reasons){ + return isNotOk(null, reasons); + } + + public static Result isNotOk(String title, List reasons){ + List reasonList = new ArrayList<>(); + + if(title != null) + reasonList.add(Reason.conflict(title)); + + for(String reasonString : reasons){ + reasonList.add(Reason.simple(reasonString)); + } + + return new Result(false, reasonList); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/common/Sync.java b/src/main/java/com/jverbruggen/jrides/common/Sync.java new file mode 100644 index 00000000..3ead454d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/common/Sync.java @@ -0,0 +1,22 @@ +package com.jverbruggen.jrides.common; + +import com.jverbruggen.jrides.JRidesPlugin; +import org.bukkit.Bukkit; + +public class Sync { + public static void runSynced(Runnable runnable){ + Bukkit.getScheduler().runTask(JRidesPlugin.getBukkitPlugin(), runnable); + } + + public static int runRepeated(Runnable runnable, long interval){ + return Bukkit.getScheduler().runTaskTimer(JRidesPlugin.getBukkitPlugin(), runnable, interval, interval).getTaskId(); + } + + public static void stopTask(int taskId){ + Bukkit.getScheduler().cancelTask(taskId); + } + + public static void runAfter(Runnable runnable, long afterTicks) { + Bukkit.getScheduler().runTaskLater(JRidesPlugin.getBukkitPlugin(), runnable, afterTicks); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/common/permissions/Permissions.java b/src/main/java/com/jverbruggen/jrides/common/permissions/Permissions.java new file mode 100644 index 00000000..3793ecf3 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/common/permissions/Permissions.java @@ -0,0 +1,31 @@ +package com.jverbruggen.jrides.common.permissions; + +public class Permissions { + /// Default + public static final String RIDE_ENTER = "jrides.default.ride_enter"; // Allow entering a ride + public static final String RIDE_WARP = "jrides.default.warp"; // Allow warping (through menu) + public static final String COMMAND_RIDE_WARP = "jrides.command.default.warp"; // Allow warping (through command) + public static final String COMMAND_RIDES_MENU = "jrides.command.default.rides"; // Allow opening '/jrides rides' menu + + /// Operator + public static final String CABIN_OPERATE = "jrides.operator.cabin_operate"; // Allow to operate in a ride cabin + public static final String COMMAND_CONTROL = "jrides.command.operator"; // Allow '/jrides control' command + public static final String COMMAND_CONTROL_DISPATCH = "jrides.command.operator.dispatch"; // Allow '/jrides control dispatch' command + public static final String COMMAND_CONTROL_MENU = "jrides.command.operator.menu"; // Allow '/jrides control menu' command + + /// Elevated (admin) + public static final String ELEVATED_RESTRAINT_OVERRIDE = "jrides.elevated.restraint_override"; // Allow to override restraint lock + public static final String ELEVATED_OPERATOR_OVERRIDE = "jrides.elevated.operator_override"; // Allow to take over an operator in a cabin + public static final String ELEVATED_RIDE_CLOSED_ENTER_OVERRIDE = "jrides.elevated.closed_ride_enter_override"; // Allow to override closed ride entering + public static final String ELEVATED_RIDE_OPEN_STATE_CHANGE = "jrides.elevated.open_state_change"; // Allow to open or close a ride + public static final String COMMAND_ELEVATED_BASE = "jrides.command.elevated"; // Base for elevated commands (for admins) + public static final String COMMAND_ELEVATED_ADMIN_MENU = "jrides.command.elevated.admin_menu"; // Allow to open ride admin menu + public static final String COMMAND_ELEVATED_RIDE_OVERVIEW = "jrides.command.elevated.ride_overview"; // Allow for generating a ride overview map + public static final String COMMAND_ELEVATED_RIDE_COUNTER_MAP = "jrides.command.elevated.ride_counter_map"; // Allow for generating a ride counter map + public static final String COMMAND_ELEVATED_BLOCK_SECTION = "jrides.command.elevated.block_section"; // Allow for getting block section occupation message (debug) + public static final String COMMAND_ELEVATED_VISUALIZE = "jrides.command.elevated.visualize"; // Allow to visualize a coaster spline (debug) + + /// Debug + public static final String ELEVATED_STATUS_INSPECTION = "jrides.elevated.status_inspection"; // Allow to inspect coaster frames (debug) + public static final String ELEVATED_DISPATCH_PROBLEMS_DEBUG = "jrides.elevated.dispatch_problems_debug"; +} diff --git a/src/main/java/com/jverbruggen/jrides/common/startup/StartMessage.java b/src/main/java/com/jverbruggen/jrides/common/startup/StartMessage.java new file mode 100644 index 00000000..87ddd764 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/common/startup/StartMessage.java @@ -0,0 +1,36 @@ +package com.jverbruggen.jrides.common.startup; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; + +import java.util.List; +import java.util.logging.Logger; + +public class StartMessage { + private static String splashLogo = """ + _ _ _ \s + (_)_ __(_) __| | ___ ___\s + | | '__| |/ _` |/ _ \\/ __| + | | | | | (_| | __/\\__ \\ + _/ |_| |_|\\__,_|\\___||___/ + |__/ \s + """; + private static String enabled = " E N A B L E D"; + private static String disabled = " D I S A B L E D"; + + public static void sendEnabledMessage(){ + Logger logger = ServiceProvider.getSingleton(Logger.class); + sendSplash(logger); + logger.info("\u001b[32m" + enabled + " - " + JRidesPlugin.getVersion() + "\u001b[0m"); + } + + public static void sendDisabledMessage(){ + Logger logger = ServiceProvider.getSingleton(Logger.class); + sendSplash(logger); + logger.info("\u001b[31m" + disabled + " - " + JRidesPlugin.getVersion() + "\u001b[0m"); + } + + private static void sendSplash(Logger logger){ + List.of(splashLogo.split("\n")).forEach(line -> logger.info("\u001b[33m" + line + "\u001b[0m")); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/ConfigManager.java b/src/main/java/com/jverbruggen/jrides/config/ConfigManager.java new file mode 100644 index 00000000..523056f7 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/ConfigManager.java @@ -0,0 +1,248 @@ +package com.jverbruggen.jrides.config; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.config.coaster.CoasterConfig; +import com.jverbruggen.jrides.config.flatride.FlatRideConfig; +import com.jverbruggen.jrides.config.ride.RidesConfig; +import com.jverbruggen.jrides.config.trigger.TriggerConfig; +import com.jverbruggen.jrides.config.trigger.TriggerConfigFactory; +import com.jverbruggen.jrides.models.ride.RideType; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.InvalidConfigurationException; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +public class ConfigManager { + private final JavaPlugin plugin; + + public ConfigManager(JavaPlugin plugin) { + this.plugin = plugin; + } + + private File getFile(String fileName){ + File rootFolder = plugin.getDataFolder(); + File file = new File(rootFolder, fileName); + if(!file.exists()){ + file.getParentFile().mkdirs(); + } + return file; + } + + public YamlConfiguration getYamlConfiguration(String fileName){ + File file = getFile(fileName); + + YamlConfiguration configuration = new YamlConfiguration(); + try { + configuration.load(file); + } catch (IOException | InvalidConfigurationException e) { + return null; + } + return configuration; + } + + public YamlConfiguration getOrCreateConfiguration(String fileName){ + YamlConfiguration found = getYamlConfiguration(fileName); + if(found != null) return found; + + found = new YamlConfiguration(); + File file = getFile(fileName); + try { + file.createNewFile(); + found.load(file); + } catch (IOException | InvalidConfigurationException e) { + e.printStackTrace(); + JRidesPlugin.getLogger().severe("Could not create configuration file with name '" + fileName + "'!!"); + } + + return found; + } + + public String getPluginName() { + return this.plugin.getDescription().getName(); + } + + private String prepareConfigString(String configString) { + int lastLine = 0; + int headerLine = 0; + + String[] lines = configString.split("\n"); + StringBuilder config = new StringBuilder(""); + String[] arrayOfString1; + int j = (arrayOfString1 = lines).length; + for (int i = 0; i < j; i++) { + String line = arrayOfString1[i]; + if (line.startsWith(getPluginName() + "_COMMENT")) { + String comment = "#" + line.trim().substring(line.indexOf(":") + 1); + if (comment.startsWith("# +-")) { + if (headerLine == 0) { + config.append(comment + "\n"); + lastLine = 0; + headerLine = 1; + } else if (headerLine == 1) { + config.append(comment + "\n\n"); + lastLine = 0; + headerLine = 0; + } + } else { + String normalComment; + if (comment.startsWith("# ' ")) { + normalComment = + + comment.substring(0, comment.length() - 1).replaceFirst("# ' ", "# "); + } else { + normalComment = comment; + } + if (lastLine == 0) { + config.append(normalComment + "\n"); + } else if (lastLine == 1) { + config.append("\n" + normalComment + "\n"); + } + lastLine = 0; + } + } else { + config.append(line + "\n"); + lastLine = 1; + } + } + return config.toString(); + } + + public void saveConfig(String configString, File file) { + String configuration = prepareConfigString(configString); + try { + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write(configuration); + writer.flush(); + writer.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void saveConfig(YamlConfiguration configuration, String fileName){ + File file = getFile(fileName); + saveConfig(configuration.saveToString(), file); + } + + public String getCoasterFolder(String rideIdentifier){ + return "coasters/" + rideIdentifier; + } + + public String getFlatrideFolder(String rideIdentifier){ + return "flatrides/" + rideIdentifier; + } + + public String getTriggerFolder(RideType rideType, String rideIdentifier){ + return switch (rideType){ + case COASTER -> getCoasterFolder(rideIdentifier) + "/triggers"; + case FLATRIDE -> getFlatrideFolder(rideIdentifier) + "/triggers"; + }; + } + + public ConfigurationSection getAllEffectsConfigSection(String rideIdentifier, String trackIdentifier){ + String fileName = getCoasterFolder(rideIdentifier) + "/" + rideIdentifier + "." + trackIdentifier + ".trigger.yml"; + YamlConfiguration yamlConfiguration = getYamlConfiguration(fileName); + if(yamlConfiguration == null){ + JRidesPlugin.getLogger().warning("No trigger file for ride " + rideIdentifier); + return null; + } + + return yamlConfiguration.getConfigurationSection("triggers"); + } + + public TriggerConfig getTriggerConfig(RideType rideType, String rideIdentifier, String effectName){ + String fileName = getTriggerFolder(rideType, rideIdentifier) + "/" + effectName + ".yml"; + YamlConfiguration yamlConfiguration = getYamlConfiguration(fileName); + if(yamlConfiguration == null){ + JRidesPlugin.getLogger().severe("Trigger " + effectName + " not found for ride " + rideIdentifier); + return null; + } + + TriggerConfigFactory triggerConfigFactory = ServiceProvider.getSingleton(TriggerConfigFactory.class); + return triggerConfigFactory.fromConfigurationSection(rideIdentifier, effectName, yamlConfiguration.getConfigurationSection("trigger")); + } + + public CoasterConfig getCoasterConfig(String rideIdentifier){ + String fileName = getCoasterFolder(rideIdentifier) + "/" + rideIdentifier + ".coaster.yml"; + YamlConfiguration yamlConfiguration = getYamlConfiguration(fileName); + if(yamlConfiguration == null){ + JRidesPlugin.getLogger().severe(rideIdentifier + ".coaster.yml config not found for " + rideIdentifier); + return null; + } + + return CoasterConfig.fromConfigurationSection(yamlConfiguration.getConfigurationSection("config")); + } + + public FlatRideConfig getFlatRideConfig(String rideIdentifier){ + String fileName = getFlatrideFolder(rideIdentifier) + "/" + rideIdentifier + ".flatride.yml"; + YamlConfiguration yamlConfiguration = getYamlConfiguration(fileName); + if(yamlConfiguration == null){ + JRidesPlugin.getLogger().severe(rideIdentifier + ".flatride.yml config not found for " + rideIdentifier); + return null; + } + + return FlatRideConfig.fromConfigurationSection(yamlConfiguration.getConfigurationSection("config")); + } + + public RidesConfig getRideConfig(){ + String fileName = "rides.yml"; + YamlConfiguration yamlConfiguration = getYamlConfiguration(fileName); + if(yamlConfiguration == null) { + JRidesPlugin.getLogger().severe("rides.yml config not found"); + return null; + } + + return RidesConfig.fromConfigurationSection(yamlConfiguration.getConfigurationSection("config")); + } + + public void updateConfigFile(String configFile, String yamlRootKey, Object object){ + YamlConfiguration configuration = getOrCreateConfiguration(configFile); + + configuration.set(yamlRootKey, object); + + saveConfig(configuration, configFile); + } + + public Optional getConfigFileObject(String configFile, String yamlRootKey, Class clazz){ + YamlConfiguration configuration = getOrCreateConfiguration(configFile); + + if(!configuration.contains(yamlRootKey)) + return Optional.empty(); + + Object tObject = configuration.get(yamlRootKey); + T t; + try{ + t = clazz.cast(tObject); + }catch(ClassCastException exception){ + throw new RuntimeException("Config file " + configFile + " did not contain object of type " + clazz.getTypeName()); + } + + assert t != null; + return Optional.of(t); + } + + public Map getLanguageFile() { + YamlConfiguration yamlConfiguration = getYamlConfiguration("language.yml"); + if(yamlConfiguration == null) return null; + + ConfigurationSection configurationSection = yamlConfiguration.getConfigurationSection("language"); + Set keys = configurationSection.getKeys(false); + Map result = new HashMap<>(); + + for(String key : keys){ + result.put(key, configurationSection.getString(key)); + } + + return result; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/CoasterConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/CoasterConfig.java new file mode 100644 index 00000000..fd845bcf --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/CoasterConfig.java @@ -0,0 +1,101 @@ +package com.jverbruggen.jrides.config.coaster; + +import com.jverbruggen.jrides.config.coaster.objects.*; +import com.jverbruggen.jrides.config.coaster.objects.item.ItemStackConfig; +import com.jverbruggen.jrides.config.gates.GatesConfig; +import com.jverbruggen.jrides.config.ride.AbstractRideConfig; +import com.jverbruggen.jrides.config.ride.RideCounterMapConfigs; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import org.bukkit.ChatColor; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +public class CoasterConfig extends AbstractRideConfig { + private final TrackConfig track; + private final VehiclesConfig vehicles; + private final CartSpecConfig cartSpec; + private final double gravityConstant; + private final double dragConstant; + private final ControllerConfig controllerConfig; + private final int rideOverviewMapId; + + public CoasterConfig(String manifestVersion, String identifier, String displayName, List displayDescription, + ItemStackConfig displayItem, PlayerLocation warpLocation, PlayerLocation customEjectLocation, TrackConfig track, + InteractionEntitiesConfig interactionEntities, + VehiclesConfig vehicles, CartSpecConfig cartSpec, GatesConfig gates, double gravityConstant, double dragConstant, + ControllerConfig controllerConfig, SoundsConfig soundsConfig, int rideOverviewMapId, boolean canExitDuringRide, + RideCounterMapConfigs rideCounterMapConfigs, boolean debugMode) { + super(manifestVersion, identifier, displayName, displayDescription, displayItem, warpLocation, customEjectLocation, gates, soundsConfig, canExitDuringRide, interactionEntities, rideCounterMapConfigs, debugMode); + this.track = track; + this.vehicles = vehicles; + this.cartSpec = cartSpec; + this.gravityConstant = gravityConstant; + this.dragConstant = dragConstant; + this.controllerConfig = controllerConfig; + this.rideOverviewMapId = rideOverviewMapId; + } + + public TrackConfig getTrack() { + return track; + } + + public VehiclesConfig getVehicles() { + return vehicles; + } + + public CartSpecConfig getCartSpec() { + return cartSpec; + } + + public double getGravityConstant() { + return gravityConstant; + } + + public double getDragConstant() { + return dragConstant; + } + + public ControllerConfig getControllerConfig() { + return controllerConfig; + } + + public int getRideOverviewMapId() { + return rideOverviewMapId; + } + + public static CoasterConfig fromConfigurationSection(ConfigurationSection configurationSection) { + String manifestVersion = getString(configurationSection, "manifestVersion"); + String identifier = getString(configurationSection, "identifier"); + String displayName = getString(configurationSection, "displayName"); + + List displayDescription = Arrays.stream(getString(configurationSection, "displayDescription", "").split("\\\\n")) + .map(d -> ChatColor.GRAY + d) + .collect(Collectors.toList()); + if(displayDescription.size() == 1 && ChatColor.stripColor(displayDescription.get(0)).equals("")) + displayDescription.clear(); + + ItemStackConfig displayItem = ItemStackConfig.fromConfigurationSection(configurationSection.getConfigurationSection("displayItem")); + PlayerLocation warpLocation = PlayerLocation.fromDoubleList(configurationSection.getDoubleList("warpLocation")); + PlayerLocation customEjectLocation = PlayerLocation.fromDoubleList(getDoubleList(configurationSection, "customEjectLocation", null)); + double gravityConstant = getDouble(configurationSection, "gravityConstant", 0.15); + double dragConstant = getDouble(configurationSection, "dragConstant", 0.9993); + TrackConfig track = TrackConfig.fromConfigurationSection(getConfigurationSection(configurationSection, "track")); + VehiclesConfig vehicles = VehiclesConfig.fromConfigurationSection(getConfigurationSection(configurationSection, "vehicles")); + CartSpecConfig cartSpec = CartSpecConfig.fromConfigurationSection(getConfigurationSection(configurationSection, "cartSpec")); + GatesConfig gates = GatesConfig.fromConfigurationSection(configurationSection.getConfigurationSection("gates")); + InteractionEntitiesConfig interactionEntities = InteractionEntitiesConfig.fromConfigurationSection(getConfigurationSection(configurationSection, "interactionEntities")); + SoundsConfig sounds = SoundsConfig.fromConfigurationSection(configurationSection.getConfigurationSection("sounds")); + ControllerConfig controllerConfig = ControllerConfig.fromConfigurationSection(configurationSection.getConfigurationSection("controller")); + int rideOverviewMapId = getInt(configurationSection, "rideOverviewMapId", -1); + boolean canExitDuringRide = getBoolean(configurationSection, "canExitDuringRide", false); + RideCounterMapConfigs rideCounterMapConfigs = RideCounterMapConfigs.fromConfigurationSection(identifier, configurationSection.getConfigurationSection("rideCounterMaps")); + boolean debugMode = getBoolean(configurationSection, "debugMode", false); + + return new CoasterConfig(manifestVersion, identifier, displayName, displayDescription, displayItem, warpLocation, customEjectLocation, track, interactionEntities, vehicles, + cartSpec, gates, gravityConstant, dragConstant, controllerConfig, sounds, rideOverviewMapId, + canExitDuringRide, rideCounterMapConfigs, debugMode); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/BaseConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/BaseConfig.java new file mode 100644 index 00000000..2b31216a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/BaseConfig.java @@ -0,0 +1,208 @@ +package com.jverbruggen.jrides.config.coaster.objects; + +import com.jverbruggen.jrides.config.utils.integersupplier.CycleIntegerSupplier; +import com.jverbruggen.jrides.config.utils.integersupplier.RandomIntegerSupplier; +import com.jverbruggen.jrides.config.utils.integersupplier.SimpleIntegerSupplier; +import org.bukkit.configuration.ConfigurationSection; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; +import java.util.stream.Collectors; + +public abstract class BaseConfig { + private static String getAvailableKeys(ConfigurationSection configurationSection){ + if(configurationSection == null) return ""; + return String.join(", ", configurationSection.getKeys(false)); + } + + private static void assertPresence(ConfigurationSection configurationSection, String key){ + if(configurationSection == null || !configurationSection.contains(key)){ + throw new RuntimeException("Missing key in config: '" + key + "', available: " + getAvailableKeys(configurationSection)); + } + } + + private static void assertPresence(Map config, String key){ + if(config == null || !config.containsKey(key)){ + throw new RuntimeException("Missing key in config: " + key); + } + } + + private static boolean isPresent(ConfigurationSection configurationSection, String key){ + if(configurationSection == null) return false; + return configurationSection.contains(key); + } + + private static boolean isPresent(Map config, String key){ + if(config == null) return false; + return config.containsKey(key); + } + + protected static double getDouble(ConfigurationSection configurationSection, String key){ + assertPresence(configurationSection, key); + return configurationSection.getDouble(key); + } + + protected static Double getDoubleObj(ConfigurationSection configurationSection, String key){ + assertPresence(configurationSection, key); + return configurationSection.getDouble(key); + } + + protected static double getDouble(ConfigurationSection configurationSection, String key, double defaultValue){ + if(!isPresent(configurationSection, key)) return defaultValue; + return getDouble(configurationSection, key); + } + + protected static Double getDoubleObj(ConfigurationSection configurationSection, String key, Double defaultValue){ + if(!isPresent(configurationSection, key)) return defaultValue; + return getDoubleObj(configurationSection, key); + } + + protected static int getInt(ConfigurationSection configurationSection, String key){ + assertPresence(configurationSection, key); + return configurationSection.getInt(key); + } + + protected static int getInt(ConfigurationSection configurationSection, String key, int defaultValue){ + if(!isPresent(configurationSection, key)) return defaultValue; + return getInt(configurationSection, key); + } + + protected static Supplier getIntSupplier(ConfigurationSection configurationSection, String key){ + assertPresence(configurationSection, key); + Object value = configurationSection.get(key); + if(value instanceof List){ + List ints = ((List)value).stream().map(o -> (int)o).toList(); + if(ints.size() != 2) throw new RuntimeException("Range can only have 2 items"); + return new RandomIntegerSupplier(ints.get(0), ints.get(1)); + }else if(value instanceof String sValue && sValue.startsWith("<")){ + List ints = Arrays.stream(sValue.substring(1, sValue.length() - 1).replace(" ", "").split(",")) + .map(Integer::parseInt) + .toList(); + return new CycleIntegerSupplier(ints); + } + + assert value instanceof Integer; + return new SimpleIntegerSupplier((int) value); + } + + protected static Supplier getIntSupplier(ConfigurationSection configurationSection, String key, int defaultValue){ + if(!isPresent(configurationSection, key)) return new SimpleIntegerSupplier(defaultValue); + return getIntSupplier(configurationSection, key); + } + + protected static String getString(Map config, String key, String defaultValue){ + if(!isPresent(config, key)) return defaultValue; + return (String) config.get(key); + } + + protected static String getString(ConfigurationSection configurationSection, String key, String defaultValue){ + if(!isPresent(configurationSection, key)) return defaultValue; + return configurationSection.getString(key); + } + + protected static String getString(Map config, String key){ + assertPresence(config, key); + return (String) config.get(key); + } + + protected static String getString(ConfigurationSection configurationSection, String key){ + assertPresence(configurationSection, key); + return configurationSection.getString(key); + } + + protected static boolean getBoolean(ConfigurationSection configurationSection, String key, boolean defaultValue) { + if(!isPresent(configurationSection, key)) return defaultValue; + return configurationSection.getBoolean(key); + } + + protected static boolean getBoolean(ConfigurationSection configurationSection, String key) { + assertPresence(configurationSection, key); + return configurationSection.getBoolean(key); + } + + protected static @Nullable ConfigurationSection getConfigurationSection(ConfigurationSection configurationSection, String key){ + if(!isPresent(configurationSection, key)) return null; + return configurationSection.getConfigurationSection(key); + } + + protected static List getStringList(ConfigurationSection configurationSection, String key){ + assertPresence(configurationSection, key); + return configurationSection.getStringList(key); + } + + protected static List getStringList(ConfigurationSection configurationSection, String key, List defaultValue){ + if(!isPresent(configurationSection, key)) return defaultValue; + return configurationSection.getStringList(key); + } + + protected static List getDoubleList(ConfigurationSection configurationSection, String key){ + assertPresence(configurationSection, key); + + return configurationSection.getList(key) + .stream() + .map(BaseConfig::toDouble) + .collect(Collectors.toList()); + } + + protected static List getDoubleList(ConfigurationSection configurationSection, String key, List defaultValue){ + if(!isPresent(configurationSection, key)) return defaultValue; + return getDoubleList(configurationSection, key); + } + + protected static List> getDoubleListList(ConfigurationSection configurationSection, String key){ + assertPresence(configurationSection, key); + + return configurationSection.getList(key) + .stream() + .map(obj -> ((List) obj).stream() + .map(BaseConfig::toDouble) + .collect(Collectors.toList())) + .collect(Collectors.toList()); + } + + protected static List> getDoubleListList(ConfigurationSection configurationSection, String key, List> defaultValue){ + if(!isPresent(configurationSection, key)) return defaultValue; + return getDoubleListList(configurationSection, key); + } + + protected static double toDouble(Object object){ + if(object instanceof Double){ + return (double) object; + }else if(object instanceof Integer){ + return ((Integer)object).doubleValue(); + }else throw new RuntimeException("Cannot convert " + object + " to double"); + } + + protected static List getIntegerList(ConfigurationSection configurationSection, String key){ + assertPresence(configurationSection, key); + + return configurationSection.getList(key) + .stream() + .map(BaseConfig::toInteger) + .collect(Collectors.toList()); + } + + protected static List getIntegerList(ConfigurationSection configurationSection, String key, List defaultValue){ + if(!isPresent(configurationSection, key)) return defaultValue; + return getIntegerList(configurationSection, key); + } + + protected static int toInteger(Object object){ + if(object instanceof Integer){ + return (Integer) object; + }else throw new RuntimeException("Cannot convert " + object + " to integer"); + } + + protected static List createDoubleList(double a, double b, double c){ + List doubleList = new ArrayList<>(); + doubleList.add(a); + doubleList.add(b); + doubleList.add(c); + return doubleList; + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/CartSpecConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/CartSpecConfig.java new file mode 100644 index 00000000..6b33d59c --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/CartSpecConfig.java @@ -0,0 +1,57 @@ +package com.jverbruggen.jrides.config.coaster.objects; + +import com.jverbruggen.jrides.config.coaster.objects.cart.CartTypeSpecConfig; +import org.bukkit.configuration.ConfigurationSection; + +import javax.annotation.Nullable; + +public class CartSpecConfig { + private final CartTypeSpecConfig _default; + private final CartTypeSpecConfig head; + private final CartTypeSpecConfig tail; + + public CartSpecConfig(CartTypeSpecConfig _default, CartTypeSpecConfig head, CartTypeSpecConfig tail) { + this._default = _default; + this.head = head; + this.tail = tail; + } + + public CartTypeSpecConfig getDefault() { + return _default; + } + + public CartTypeSpecConfig getHead() { + return head; + } + + public CartTypeSpecConfig getTail() { + return tail; + } + + public boolean hasHead(){ + return head != null; + } + + public boolean hasTail(){ + return tail != null; + } + + public static CartSpecConfig fromConfigurationSection(@Nullable ConfigurationSection configurationSection) { + if(configurationSection == null) + return new CartSpecConfig(CartTypeSpecConfig.fromConfigurationSection(null), null, null); + + CartTypeSpecConfig _default = CartTypeSpecConfig.fromConfigurationSection(configurationSection.getConfigurationSection("default")); + CartTypeSpecConfig head = null; + CartTypeSpecConfig tail = null; + + if(configurationSection.contains("head")){ + head = CartTypeSpecConfig.fromConfigurationSection(configurationSection.getConfigurationSection("head")); + } + if(configurationSection.contains("tail")){ + tail = CartTypeSpecConfig.fromConfigurationSection(configurationSection.getConfigurationSection("tail")); + } + + return new CartSpecConfig(_default, head, tail); + } +} + diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/ControllerConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/ControllerConfig.java new file mode 100644 index 00000000..090e2341 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/ControllerConfig.java @@ -0,0 +1,41 @@ +package com.jverbruggen.jrides.config.coaster.objects; + +import com.jverbruggen.jrides.config.coaster.objects.controller.DualControllerSpecConfig; +import org.bukkit.configuration.ConfigurationSection; + +public class ControllerConfig extends BaseConfig { + public static final String CONTROLLER_DEFAULT = "default"; + public static final String CONTROLLER_ALTERNATE = "alternate"; + public static final String CONTROLLER_SIMULTANEOUS = "simultaneous"; + + private String type; + private DualControllerSpecConfig dualControllerSpecConfig; + + public ControllerConfig(String type, DualControllerSpecConfig dualControllerSpecConfig) { + this.type = type; + this.dualControllerSpecConfig = dualControllerSpecConfig; + } + + public String getType() { + return type; + } + + public DualControllerSpecConfig getAlternateControllerSpecConfig() { + return dualControllerSpecConfig; + } + + public static ControllerConfig fromConfigurationSection(ConfigurationSection configurationSection) { + if(configurationSection == null) return null; + + String type = getString(configurationSection, "type", "default"); + DualControllerSpecConfig dualControllerSpecConfig = null; + + if(type.equalsIgnoreCase(CONTROLLER_ALTERNATE)) + dualControllerSpecConfig = DualControllerSpecConfig.fromConfigurationSection(configurationSection.getConfigurationSection("spec")); + else if(type.equalsIgnoreCase(CONTROLLER_SIMULTANEOUS)) + dualControllerSpecConfig = DualControllerSpecConfig.fromConfigurationSection(configurationSection.getConfigurationSection("spec")); + + return new ControllerConfig(type, dualControllerSpecConfig); + } +} + diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/InteractionEntitiesConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/InteractionEntitiesConfig.java new file mode 100644 index 00000000..86c8b3e9 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/InteractionEntitiesConfig.java @@ -0,0 +1,61 @@ +package com.jverbruggen.jrides.config.coaster.objects; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.config.coaster.objects.cart.ModelConfig; +import com.jverbruggen.jrides.event.action.OperateRideAction; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.viewport.ViewportManager; +import org.bukkit.configuration.ConfigurationSection; + +import javax.annotation.Nullable; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class InteractionEntitiesConfig extends BaseConfig { + private final Map interactionEntities; + + public InteractionEntitiesConfig(Map interactionEntities) { + this.interactionEntities = interactionEntities; + } + + public InteractionEntitiesConfig(){ + this.interactionEntities = new HashMap<>(); + } + + public void spawnEntities(RideHandle rideHandle){ + ViewportManager viewportManager = ServiceProvider.getSingleton(ViewportManager.class); + + for(Map.Entry entry : interactionEntities.entrySet()){ + ModelConfig modelConfig = entry.getValue(); + Vector3 spawnPosition = modelConfig.getPosition(); + Quaternion spawnRotation = modelConfig.getRotation(); + String customName = "Controller"; + VirtualEntity virtualEntity = modelConfig.getItemConfig().spawnEntity(viewportManager, spawnPosition, spawnRotation, customName); + + virtualEntity.setCustomAction(new OperateRideAction()); + virtualEntity.setBelongsToRide(rideHandle); + } + } + + public static InteractionEntitiesConfig fromConfigurationSection(@Nullable ConfigurationSection configurationSection){ + if(configurationSection == null) + return new InteractionEntitiesConfig(); + + Set keys = configurationSection.getKeys(false); + + Map entityLocations = new HashMap<>(); + + for(String key : keys){ + ConfigurationSection keyConfigurationSection = configurationSection.getConfigurationSection(key); + ModelConfig modelConfig = ModelConfig.fromConfigurationSection(keyConfigurationSection); + + entityLocations.put(key, modelConfig); + } + + return new InteractionEntitiesConfig(entityLocations); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/SoundsConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/SoundsConfig.java new file mode 100644 index 00000000..a84eca84 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/SoundsConfig.java @@ -0,0 +1,48 @@ +package com.jverbruggen.jrides.config.coaster.objects; + +import org.bukkit.configuration.ConfigurationSection; + +public class SoundsConfig { + private final String onrideWind; + private final String restraintOpen; + private final String restraintClose; + private final String dispatch; + + public SoundsConfig(String onrideWind, String restraintOpen, String restraintClose, String dispatch) { + this.onrideWind = onrideWind; + this.restraintOpen = restraintOpen; + this.restraintClose = restraintClose; + this.dispatch = dispatch; + } + + public SoundsConfig() { + this(null, null, null, null); + } + + public String getOnrideWind() { + return onrideWind; + } + + public String getRestraintOpen() { + return restraintOpen; + } + + public String getRestraintClose() { + return restraintClose; + } + + public String getDispatch() { + return dispatch; + } + + public static SoundsConfig fromConfigurationSection(ConfigurationSection configurationSection){ + if(configurationSection == null) return new SoundsConfig(); + + String onrideWind = configurationSection.contains("onrideWind") ? configurationSection.getString("onrideWind") : null; + String restraintOpen = configurationSection.contains("restraintOpen") ? configurationSection.getString("restraintOpen") : null; + String restraintClose = configurationSection.contains("restraintClose") ? configurationSection.getString("restraintClose") : null; + String dispatch = configurationSection.contains("dispatch") ? configurationSection.getString("dispatch") : null; + + return new SoundsConfig(onrideWind, restraintOpen, restraintClose, dispatch); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/TrackConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/TrackConfig.java new file mode 100644 index 00000000..a43380ba --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/TrackConfig.java @@ -0,0 +1,76 @@ +package com.jverbruggen.jrides.config.coaster.objects; + +import com.jverbruggen.jrides.config.coaster.objects.section.base.SectionConfig; +import org.bukkit.configuration.ConfigurationSection; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +public class TrackConfig { + private final List position; + private final List sections; + private final List parts; + private final boolean correctlyLoaded; + + public TrackConfig(List position, List sections, List parts) { + this.position = position; + this.sections = sections; + this.parts = parts; + this.correctlyLoaded = true; + } + + public TrackConfig(){ + this.position = new ArrayList<>(); + this.sections = new ArrayList<>(); + this.parts = new ArrayList<>(); + this.correctlyLoaded = false; + } + + public List getPosition() { + return position; + } + + public List getSections() { + return sections; + } + + public List getParts() { + return parts; + } + + public boolean isCorrectlyLoaded() { + return correctlyLoaded; + } + + public static TrackConfig fromConfigurationSection(@Nullable ConfigurationSection configurationSection) { + if(configurationSection == null) return new TrackConfig(); + + List position = configurationSection.getFloatList("position"); + List parts = configurationSection.getStringList("parts"); + + List sections = new ArrayList<>(); + ConfigurationSection configurationSectionSections = configurationSection.getConfigurationSection("sections"); + Set sectionsKeys = configurationSectionSections.getKeys(false); + for(String sectionKey : sectionsKeys){ + ConfigurationSection sectionSpec = configurationSectionSections.getConfigurationSection(sectionKey); + + String track = "spline"; + assert sectionSpec != null; + if(sectionSpec.contains("track")){ + track = sectionSpec.getString("track"); + } + + assert track != null; + if(track.equalsIgnoreCase("spline")){ + sections.add(SectionConfig.fromConfigurationSection(sectionSpec, sectionKey)); + }else if(track.equalsIgnoreCase("straight")){ + throw new RuntimeException("Straight track not implemented yet"); + } + } + + return new TrackConfig(position, sections, parts); + } +} + diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/VehiclesConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/VehiclesConfig.java new file mode 100644 index 00000000..21c3fc2a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/VehiclesConfig.java @@ -0,0 +1,38 @@ +package com.jverbruggen.jrides.config.coaster.objects; + +import org.bukkit.configuration.ConfigurationSection; + +public class VehiclesConfig extends BaseConfig { + private final int trains; + private final int carts; + private final int cartDistance; + + public VehiclesConfig(int trains, int carts, int cartDistance) { + this.trains = trains; + this.carts = carts; + this.cartDistance = cartDistance; + } + + public int getCarts() { + return carts; + } + + public int getTrains() { + return trains; + } + + public int getCartDistance() { + return cartDistance; + } + + public static VehiclesConfig fromConfigurationSection(ConfigurationSection configurationSection) { + int trains = getInt(configurationSection, "trains", 1); + int carts = getInt(configurationSection, "carts", 1); + int cartDistance = getInt(configurationSection, "cartDistance", 20); + + if(cartDistance < 20) + throw new RuntimeException("Cart Distances for less than 20 frames are not supported"); + + return new VehiclesConfig(trains, carts, cartDistance); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/cart/CartSeatsConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/cart/CartSeatsConfig.java new file mode 100644 index 00000000..6a391cf7 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/cart/CartSeatsConfig.java @@ -0,0 +1,29 @@ +package com.jverbruggen.jrides.config.coaster.objects.cart; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.math.Vector3PlusYaw; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.List; +import java.util.stream.Collectors; + +public class CartSeatsConfig extends BaseConfig { + private List positions; + + public CartSeatsConfig(List positions) { + this.positions = positions; + } + + public List getPositions() { + return positions; + } + + public static CartSeatsConfig fromConfigurationSection(ConfigurationSection configurationSection) { + List> positions = getDoubleListList(configurationSection, "positions", List.of()); + List vectors = positions.stream() + .map(Vector3PlusYaw::fromDoubleList) + .collect(Collectors.toList()); + return new CartSeatsConfig(vectors); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/cart/CartTypeSpecConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/cart/CartTypeSpecConfig.java new file mode 100644 index 00000000..89284fff --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/cart/CartTypeSpecConfig.java @@ -0,0 +1,30 @@ +package com.jverbruggen.jrides.config.coaster.objects.cart; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +import javax.annotation.Nullable; + +public class CartTypeSpecConfig extends BaseConfig { + private final ModelConfig model; + private final CartSeatsConfig seats; + + public CartTypeSpecConfig(ModelConfig model, CartSeatsConfig seats) { + this.model = model; + this.seats = seats; + } + + public ModelConfig getModel() { + return model; + } + + public CartSeatsConfig getSeats() { + return seats; + } + + public static CartTypeSpecConfig fromConfigurationSection(@Nullable ConfigurationSection configurationSection) { + ModelConfig model = ModelConfig.fromConfigurationSection(getConfigurationSection(configurationSection, "model")); + CartSeatsConfig seats = CartSeatsConfig.fromConfigurationSection(getConfigurationSection(configurationSection, "seats")); + return new CartTypeSpecConfig(model, seats); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/cart/ModelConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/cart/ModelConfig.java new file mode 100644 index 00000000..65203b27 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/cart/ModelConfig.java @@ -0,0 +1,67 @@ +package com.jverbruggen.jrides.config.coaster.objects.cart; + +import com.jverbruggen.jrides.animator.flatride.rotor.FlatRideModel; +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.config.coaster.objects.item.ItemConfig; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.state.viewport.ViewportManager; +import org.bukkit.configuration.ConfigurationSection; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +public class ModelConfig extends BaseConfig { + private final ItemConfig itemConfig; + private final Vector3 position; + private final Quaternion rotation; + + public ModelConfig(ItemConfig itemConfig, Vector3 position, Quaternion rotation) { + this.itemConfig = itemConfig; + this.position = position; + this.rotation = rotation; + } + + public Vector3 getPosition() { + return position; + } + + public Quaternion getRotation() { + return rotation; + } + + public ItemConfig getItemConfig() { + return itemConfig; + } + + public FlatRideModel toFlatRideModel(Vector3 rootPosition, ViewportManager viewportManager){ + Vector3 spawnPosition = Vector3.add(rootPosition, position); + VirtualEntity virtualEntity = itemConfig.spawnEntity(viewportManager, spawnPosition, new Quaternion(), null); + + return new FlatRideModel(virtualEntity, position.clone(), rotation.clone()); + } + + public static ModelConfig fromConfigurationSection(@Nullable ConfigurationSection configurationSection) { + if(configurationSection == null) return new ModelConfig(null, Vector3.zero(), new Quaternion()); + + ItemConfig itemConfig = ItemConfig.fromConfigurationSection(configurationSection); + + Vector3 vector = Vector3.fromDoubleList(getDoubleList(configurationSection, "position", List.of(0d,0d,0d))); + Quaternion rotation = Quaternion.fromDoubleList(getDoubleList(configurationSection, "rotation", List.of(0d,0d,0d))); + + return new ModelConfig(itemConfig, vector, rotation); + } + + public static List multipleFromConfigurationSection(ConfigurationSection configurationSection){ + List modelConfigs = new ArrayList<>(); + Set keys = configurationSection.getKeys(false); + for(String key : keys){ + ModelConfig modelConfig = fromConfigurationSection(getConfigurationSection(configurationSection, key)); + modelConfigs.add(modelConfig); + } + return modelConfigs; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/controller/DualControllerSpecConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/controller/DualControllerSpecConfig.java new file mode 100644 index 00000000..326ae94f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/controller/DualControllerSpecConfig.java @@ -0,0 +1,29 @@ +package com.jverbruggen.jrides.config.coaster.objects.controller; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +public class DualControllerSpecConfig extends BaseConfig { + private String stationLeft; + private String stationRight; + + public DualControllerSpecConfig(String stationLeft, String stationRight) { + this.stationLeft = stationLeft; + this.stationRight = stationRight; + } + + public String getStationLeft() { + return stationLeft; + } + + public String getStationRight() { + return stationRight; + } + + public static DualControllerSpecConfig fromConfigurationSection(ConfigurationSection configurationSection) { + String stationLeft = getString(configurationSection, "stationLeft"); + String stationRight = getString(configurationSection, "stationRight"); + + return new DualControllerSpecConfig(stationLeft, stationRight); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/item/EntityConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/item/EntityConfig.java new file mode 100644 index 00000000..0a6f43eb --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/item/EntityConfig.java @@ -0,0 +1,34 @@ +package com.jverbruggen.jrides.config.coaster.objects.item; + +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.state.viewport.ViewportManager; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.entity.EntityType; + +import javax.annotation.Nullable; + +public class EntityConfig implements ItemConfig{ + private final EntityType entityType; + + public EntityConfig(EntityType entityType) { + this.entityType = entityType; + } + + public EntityType getEntityType() { + return entityType; + } + + @Override + public VirtualEntity spawnEntity(ViewportManager viewportManager, Vector3 spawnPosition, Quaternion spawnRotation, String customName) { + return viewportManager.spawnVirtualEntity(spawnPosition, getEntityType()); + } + + public static EntityConfig fromConfigurationSection(@Nullable ConfigurationSection configurationSection) { + if(configurationSection == null) return new EntityConfig(null); + + EntityType entityType = EntityType.valueOf(configurationSection.getString("type")); + return new EntityConfig(entityType); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/item/ItemConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/item/ItemConfig.java new file mode 100644 index 00000000..e4b2aab1 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/item/ItemConfig.java @@ -0,0 +1,23 @@ +package com.jverbruggen.jrides.config.coaster.objects.item; + +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.state.viewport.ViewportManager; +import org.bukkit.configuration.ConfigurationSection; + +import javax.annotation.Nullable; + +public interface ItemConfig { + VirtualEntity spawnEntity(ViewportManager viewportManager, Vector3 spawnPosition, Quaternion spawnRotation, String customName); + + static ItemConfig fromConfigurationSection(@Nullable ConfigurationSection configurationSection){ + if(configurationSection == null) return null; + + if(configurationSection.contains("item")) + return ItemStackConfig.fromConfigurationSection(configurationSection.getConfigurationSection("item")); + else if(configurationSection.contains("entity")) + return EntityConfig.fromConfigurationSection(configurationSection.getConfigurationSection("entity")); + else throw new RuntimeException("Model config needs an item or an entity"); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/item/ItemStackConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/item/ItemStackConfig.java new file mode 100644 index 00000000..32696526 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/item/ItemStackConfig.java @@ -0,0 +1,61 @@ +package com.jverbruggen.jrides.config.coaster.objects.item; + +import com.jverbruggen.jrides.items.ItemStackFactory; +import com.jverbruggen.jrides.models.entity.TrainModelItem; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.state.viewport.ViewportManager; +import org.bukkit.Material; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.inventory.ItemStack; + +import javax.annotation.Nullable; + +public class ItemStackConfig implements ItemConfig { + private final Material material; + private final int damage; + private final boolean unbreakable; + + public ItemStackConfig(Material material, int damage, boolean unbreakable) { + this.material = material; + this.damage = damage; + this.unbreakable = unbreakable; + } + + public ItemStackConfig() { + this.material = Material.STONE; + this.damage = 0; + this.unbreakable = false; + } + + public Material getMaterial() { + return material; + } + + public int getDamage() { + return damage; + } + + public boolean isUnbreakable() { + return unbreakable; + } + + public ItemStack createItemStack(){ + return ItemStackFactory.getCoasterStackFromConfig(this); + } + + @Override + public VirtualEntity spawnEntity(ViewportManager viewportManager, Vector3 spawnPosition, Quaternion spawnRotation, String customName) { + return viewportManager.spawnModelEntity(spawnPosition, spawnRotation, new TrainModelItem(createItemStack()), customName); + } + + public static ItemStackConfig fromConfigurationSection(@Nullable ConfigurationSection configurationSection) { + if(configurationSection == null) return new ItemStackConfig(); + + Material material = Material.valueOf(configurationSection.getString("material")); + int damage = configurationSection.getInt("damage", 0); + boolean unbreakable = configurationSection.getBoolean("unbreakable", false); + return new ItemStackConfig(material, damage, unbreakable); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/base/PointSectionConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/base/PointSectionConfig.java new file mode 100644 index 00000000..feb4a47b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/base/PointSectionConfig.java @@ -0,0 +1,88 @@ +package com.jverbruggen.jrides.config.coaster.objects.section.base; + +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.TrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.factory.TrackBehaviourFactory; +import com.jverbruggen.jrides.config.coaster.CoasterConfig; +import com.jverbruggen.jrides.config.coaster.objects.section.point.SwitchSectionSpecConfig; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.frame.SimpleFrame; +import com.jverbruggen.jrides.models.ride.factory.track.TrackDescription; +import com.jverbruggen.jrides.models.ride.section.reference.PointSectionReference; +import com.jverbruggen.jrides.models.ride.section.reference.SectionReference; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.List; + +public class PointSectionConfig extends SectionConfig { + private final int point; + private final String trackSource; + private final String nextSection; + private final SwitchSectionSpecConfig switchSectionSpecConfig; + + public PointSectionConfig(String identifier, int point, String trackSource, String type, String nextSection, SwitchSectionSpecConfig switchSectionSpecConfig) { + super(type, identifier); + this.point = point; + this.trackSource = trackSource; + this.nextSection = nextSection; + this.switchSectionSpecConfig = switchSectionSpecConfig; + } + + public int getPoint() { + return point; + } + + public String getNextSection() { + return nextSection; + } + + public String getParentTrackIdentifier() { + return trackSource; + } + + public SwitchSectionSpecConfig getSwitchSectionSpecConfig() { + return switchSectionSpecConfig; + } + + public static boolean accepts(String type){ + return switch (type) { + case "switch" -> true; + default -> false; + }; + } + + public static PointSectionConfig fromConfigurationSection(ConfigurationSection configurationSection, String sectionIdentifier) { + List range = configurationSection.getList("at"); + if(range == null) throw new RuntimeException("Point section " + sectionIdentifier + " requires 'at' keyword to define position of point section"); + + int point = (Integer)range.get(0); + String trackSource = "default"; + if(range.size() == 2) + trackSource = (String)range.get(1); + + String type = configurationSection.getString("type"); + String nextSection = configurationSection.getString("nextSection"); + + SwitchSectionSpecConfig switchSectionSpecConfig = null; + if(configurationSection.contains("switchSpec")) + switchSectionSpecConfig = SwitchSectionSpecConfig.fromConfigurationSection(configurationSection.getConfigurationSection("switchSpec")); + + return new PointSectionConfig(sectionIdentifier, point, trackSource, type, nextSection, switchSectionSpecConfig); + } + + @Override + public SectionReference build(TrackBehaviourFactory trackBehaviourFactory, List trackDescriptions, CoasterHandle coasterHandle, + CoasterConfig coasterConfig) { + String sectionIdentifier = getIdentifier(); + String nextSectionIdentifier = getNextSection(); + String parentTrackIdentifier = getParentTrackIdentifier(); + + Frame point = new SimpleFrame(getPoint()); + + TrackBehaviour trackBehaviour = trackBehaviourFactory.getTrackBehaviourFor(coasterHandle, coasterConfig, this); + if(trackBehaviour == null) return null; + + return new PointSectionReference(sectionIdentifier, point, trackBehaviour, nextSectionIdentifier, parentTrackIdentifier); + } +} + diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/base/RangedSectionConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/base/RangedSectionConfig.java new file mode 100644 index 00000000..f57c5e23 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/base/RangedSectionConfig.java @@ -0,0 +1,248 @@ +package com.jverbruggen.jrides.config.coaster.objects.section.base; + +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.TrackBehaviour; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.factory.TrackBehaviourFactory; +import com.jverbruggen.jrides.config.coaster.CoasterConfig; +import com.jverbruggen.jrides.config.coaster.objects.section.ranged.*; +import com.jverbruggen.jrides.config.coaster.objects.section.ranged.transfer.TransferSectionSpecConfig; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.frame.SimpleFrame; +import com.jverbruggen.jrides.models.ride.factory.track.TrackDescription; +import com.jverbruggen.jrides.models.ride.section.reference.RangedSectionReference; +import com.jverbruggen.jrides.models.ride.section.reference.SectionReference; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.List; + +public class RangedSectionConfig extends SectionConfig { + private final int lowerRange; + private final int upperRange; + private final boolean jumpAtStart; + private final boolean jumpAtEnd; + private final boolean forwards; + private final String trackSource; + private final String nextSection; + private final String arrivalUnlocksSection; + private final List conflictSections; + private final BlockSectionSpecConfig blockSectionSpec; + private final CoasterStationConfig stationSectionSpec; + private final BrakeSectionSpecConfig brakeSectionSpec; + private final TrimBrakeSectionSpecConfig trimBrakeSectionSpecConfig; + private final DriveSectionSpecConfig driveSectionSpec; + private final ProximityDriveSectionSpecConfig proximityDriveSectionSpecConfig; + private final DriveAndReleaseSectionSpecConfig driveAndReleaseSectionSpecConfig; + private final DriveStopDriveSectionSpecConfig driveStopDriveSectionSpecConfig; + private final StorageSectionSpecConfig storageSectionSpec; + private final TransferSectionSpecConfig transferSectionSpec; + private final LaunchSectionSpecConfig launchSectionSpecConfig; + + public RangedSectionConfig(String identifier, int lowerRange, int upperRange, boolean jumpAtStart, boolean jumpAtEnd, boolean forwards, String trackSource, String type, + String nextSection, String arrivalUnlocksSection, List conflictSections, + BlockSectionSpecConfig blockSectionSpec, CoasterStationConfig stationSectionSpec, BrakeSectionSpecConfig brakeSectionSpec, + TrimBrakeSectionSpecConfig trimBrakeSectionSpecConfig, DriveSectionSpecConfig driveSectionSpec, ProximityDriveSectionSpecConfig proximityDriveSectionSpecConfig, StorageSectionSpecConfig storageSectionSpec, TransferSectionSpecConfig transferSectionSpec, + LaunchSectionSpecConfig launchSectionSpecConfig, DriveAndReleaseSectionSpecConfig driveAndReleaseSectionSpecConfig, DriveStopDriveSectionSpecConfig driveStopDriveSectionSpecConfig) { + super(type, identifier); + this.lowerRange = lowerRange; + this.upperRange = upperRange; + this.jumpAtStart = jumpAtStart; + this.jumpAtEnd = jumpAtEnd; + this.forwards = forwards; + this.trackSource = trackSource; + this.nextSection = nextSection; + this.arrivalUnlocksSection = arrivalUnlocksSection; + this.conflictSections = conflictSections; + this.blockSectionSpec = blockSectionSpec; + this.stationSectionSpec = stationSectionSpec; + this.brakeSectionSpec = brakeSectionSpec; + this.trimBrakeSectionSpecConfig = trimBrakeSectionSpecConfig; + this.driveSectionSpec = driveSectionSpec; + this.proximityDriveSectionSpecConfig = proximityDriveSectionSpecConfig; + this.driveAndReleaseSectionSpecConfig = driveAndReleaseSectionSpecConfig; + this.storageSectionSpec = storageSectionSpec; + this.transferSectionSpec = transferSectionSpec; + this.launchSectionSpecConfig = launchSectionSpecConfig; + this.driveStopDriveSectionSpecConfig = driveStopDriveSectionSpecConfig; + } + + public String getNextSection() { + return nextSection; + } + + public List getConflictSections() { + return conflictSections; + } + + public String getArrivalUnlocksSection() { + return arrivalUnlocksSection; + } + + public int getLowerRange() { + return lowerRange; + } + + public int getUpperRange() { + return upperRange; + } + + public String getParentTrackIdentifier() { + return trackSource; + } + + public BlockSectionSpecConfig getBlockSectionSpec() { + return blockSectionSpec; + } + + public CoasterStationConfig getStationSectionSpec() { + return stationSectionSpec; + } + + public BrakeSectionSpecConfig getBrakeSectionSpec() { + return brakeSectionSpec; + } + + public TrimBrakeSectionSpecConfig getTrimBrakeSectionSpecConfig() { + return trimBrakeSectionSpecConfig; + } + + public DriveSectionSpecConfig getDriveSectionSpec() { + return driveSectionSpec; + } + + public ProximityDriveSectionSpecConfig getProximityDriveSectionSpec() { + return proximityDriveSectionSpecConfig; + } + + public DriveAndReleaseSectionSpecConfig getDriveAndReleaseSectionSpecConfig() { + return driveAndReleaseSectionSpecConfig; + } + + public DriveStopDriveSectionSpecConfig getDriveStopDriveSectionSpecConfig() { + return driveStopDriveSectionSpecConfig; + } + + public StorageSectionSpecConfig getStorageSectionSpec() { + return storageSectionSpec; + } + + public TransferSectionSpecConfig getTransferSectionSpec() { + return transferSectionSpec; + } + + public LaunchSectionSpecConfig getLaunchSectionSpecConfig() { + return launchSectionSpecConfig; + } + + public boolean isJumpAtStart() { + return jumpAtStart; + } + + public boolean isJumpAtEnd() { + return jumpAtEnd; + } + + public boolean isForwards() { + return forwards; + } + + public static boolean accepts(String type){ + return switch (type) { + case "track", "drive", "proximityDrive", "driveAndRelease", "driveStopDrive", "brake", "trim", "station", "blocksection", "transfer", "launch" -> true; + default -> false; + }; + } + + public static RangedSectionConfig fromConfigurationSection(ConfigurationSection configurationSection, String sectionIdentifier) { + String type = getString(configurationSection, "type"); + List range = configurationSection.getList("range"); + + int lowerRange = (Integer)range.get(0); + int upperRange = (Integer)range.get(1); + String trackSource = "default"; + if(range.size() == 3) + trackSource = (String)range.get(2); + String nextSection = getString(configurationSection, "nextSection"); + String arrivalUnlocks = getString(configurationSection, "arrivalUnlocks", null); + + List conflictSections = getStringList(configurationSection, "conflictSections", null); + + boolean jumpAtStart = getBoolean(configurationSection, "jumpAtStart", false); + boolean jumpAtEnd = getBoolean(configurationSection, "jumpAtEnd", false); + boolean forwards = getBoolean(configurationSection, "forwards", true); + + BlockSectionSpecConfig blockSectionSpec = null; + if(configurationSection.contains("blockSection")) + blockSectionSpec = BlockSectionSpecConfig.fromConfigurationSection(configurationSection.getConfigurationSection("blockSection")); + + CoasterStationConfig stationSectionSpec = null; + if(configurationSection.contains("stationSection")) + stationSectionSpec = CoasterStationConfig.fromConfigurationSection(configurationSection.getConfigurationSection("stationSection")); + + BrakeSectionSpecConfig brakeSectionSpec = null; + if(configurationSection.contains("brakeSection")) + brakeSectionSpec = BrakeSectionSpecConfig.fromConfigurationSection(configurationSection.getConfigurationSection("brakeSection")); + + TrimBrakeSectionSpecConfig trimBrakeSectionSpecConfig = null; + if(type.equals("trim")) + trimBrakeSectionSpecConfig = TrimBrakeSectionSpecConfig.fromConfigurationSection(configurationSection.getConfigurationSection("trimSection")); + + DriveSectionSpecConfig driveSectionSpec = null; + if(type.equals("drive")) + driveSectionSpec = DriveSectionSpecConfig.fromConfigurationSection(configurationSection.getConfigurationSection("driveSection")); + + ProximityDriveSectionSpecConfig proximityDriveSectionSpecConfig = null; + if(type.equals("proximityDrive")) + proximityDriveSectionSpecConfig = ProximityDriveSectionSpecConfig.fromConfigurationSection(configurationSection.getConfigurationSection("proximityDriveSection")); + + DriveAndReleaseSectionSpecConfig driveAndReleaseSectionSpec = null; + if(type.equals("driveAndRelease")) + driveAndReleaseSectionSpec = DriveAndReleaseSectionSpecConfig.fromConfigurationSection(configurationSection.getConfigurationSection("driveAndReleaseSection")); + + DriveStopDriveSectionSpecConfig driveStopDriveSectionSpecConfig = null; + if(type.equals("driveStopDrive")) + driveStopDriveSectionSpecConfig = DriveStopDriveSectionSpecConfig.fromConfigurationSection(configurationSection.getConfigurationSection("driveStopDriveSection")); + + StorageSectionSpecConfig storageSectionSpec = null; + if(configurationSection.contains("storageSection")) + storageSectionSpec = StorageSectionSpecConfig.fromConfigurationSection(configurationSection.getConfigurationSection("storageSection")); + + TransferSectionSpecConfig transferSectionSpec = null; + if(configurationSection.contains("transferSection")) + transferSectionSpec = TransferSectionSpecConfig.fromConfigurationSection(configurationSection.getConfigurationSection("transferSection")); + + LaunchSectionSpecConfig launchSectionSpec = null; + if(configurationSection.contains("launchSection")) + launchSectionSpec = LaunchSectionSpecConfig.fromConfigurationSection(configurationSection.getConfigurationSection("launchSection")); + + return new RangedSectionConfig(sectionIdentifier, lowerRange, upperRange, jumpAtStart, jumpAtEnd, forwards, trackSource, type, nextSection, arrivalUnlocks, conflictSections, + blockSectionSpec, stationSectionSpec, brakeSectionSpec, trimBrakeSectionSpecConfig, driveSectionSpec, proximityDriveSectionSpecConfig, storageSectionSpec, transferSectionSpec, launchSectionSpec, + driveAndReleaseSectionSpec, driveStopDriveSectionSpecConfig); + } + + @Override + public SectionReference build(TrackBehaviourFactory trackBehaviourFactory, List trackDescriptions, CoasterHandle coasterHandle, + CoasterConfig coasterConfig) { + String sectionIdentifier = getIdentifier(); + String nextSectionIdentifier = getNextSection(); + String parentTrackIdentifier = getParentTrackIdentifier(); + String arrivalUnlocks = getArrivalUnlocksSection(); + + boolean jumpAtStart = isJumpAtStart(); + boolean jumpAtEnd = isJumpAtEnd(); + boolean forwards = isForwards(); + + TrackDescription trackDescription = trackDescriptions.stream() + .filter(d -> d.getIdentifier().equalsIgnoreCase(getParentTrackIdentifier())) + .findFirst().orElseThrow(); + + Frame startFrame = new SimpleFrame(getLowerRange()); + Frame endFrame = new SimpleFrame(getUpperRange()); + + TrackBehaviour trackBehaviour = trackBehaviourFactory.getTrackBehaviourFor(coasterHandle, coasterConfig, this, trackDescription.getCycle()); + if(trackBehaviour == null) return null; + + return new RangedSectionReference(sectionIdentifier, startFrame, endFrame, trackBehaviour, nextSectionIdentifier, conflictSections, parentTrackIdentifier, + arrivalUnlocks, jumpAtStart, jumpAtEnd, forwards); + } +} + diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/base/SectionConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/base/SectionConfig.java new file mode 100644 index 00000000..a5f309d1 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/base/SectionConfig.java @@ -0,0 +1,41 @@ +package com.jverbruggen.jrides.config.coaster.objects.section.base; + +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.factory.TrackBehaviourFactory; +import com.jverbruggen.jrides.config.coaster.CoasterConfig; +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.models.ride.factory.track.TrackDescription; +import com.jverbruggen.jrides.models.ride.section.reference.SectionReference; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.List; + +public abstract class SectionConfig extends BaseConfig { + protected final String type; + protected final String identifier; + + protected SectionConfig(String type, String identifier) { + this.type = type; + this.identifier = identifier; + } + + public String getType() { + return type; + } + + public String getIdentifier() { + return identifier; + } + + public abstract SectionReference build(TrackBehaviourFactory trackBehaviourFactory, List trackDescriptions, CoasterHandle coasterHandle, + CoasterConfig coasterConfig); + + public static SectionConfig fromConfigurationSection(ConfigurationSection configurationSection, String sectionIdentifier) { + String type = getString(configurationSection, "type"); + + if(RangedSectionConfig.accepts(type)) return RangedSectionConfig.fromConfigurationSection(configurationSection, sectionIdentifier); + else if(PointSectionConfig.accepts(type)) return PointSectionConfig.fromConfigurationSection(configurationSection, sectionIdentifier); + + throw new RuntimeException("Type " + type + " is not accepted as a real section type"); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/point/SwitchSectionSpecConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/point/SwitchSectionSpecConfig.java new file mode 100644 index 00000000..a4b3583b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/point/SwitchSectionSpecConfig.java @@ -0,0 +1,38 @@ +package com.jverbruggen.jrides.config.coaster.objects.section.point; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.List; + +public class SwitchSectionSpecConfig extends BaseConfig { + private final List destinations; + private final String handler; + private final String origin; + + public SwitchSectionSpecConfig(List destinations, String handler, String origin) { + this.destinations = destinations; + this.handler = handler; + this.origin = origin; + } + + public List getDestinations() { + return destinations; + } + + public String getHandler() { + return handler; + } + + public String getOrigin() { + return origin; + } + + public static SwitchSectionSpecConfig fromConfigurationSection(ConfigurationSection configurationSection){ + List destinations = getStringList(configurationSection, "destinations"); + String handler = getString(configurationSection, "handler", "roundrobin"); + String origin = getString(configurationSection, "origin"); + + return new SwitchSectionSpecConfig(destinations, handler, origin); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/BlockSectionSpecConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/BlockSectionSpecConfig.java new file mode 100644 index 00000000..e1bbc385 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/BlockSectionSpecConfig.java @@ -0,0 +1,57 @@ +package com.jverbruggen.jrides.config.coaster.objects.section.ranged; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +public class BlockSectionSpecConfig extends BaseConfig { + private final double engage; + private final double driveSpeed; + private final boolean canSpawn; + private final double acceleration; + private final double deceleration; + private final int minWaitTicks; + + private BlockSectionSpecConfig(double engage, double driveSpeed, boolean canSpawn, double acceleration, double deceleration, int minWaitTicks) { + this.engage = engage; + this.driveSpeed = driveSpeed; + this.canSpawn = canSpawn; + this.acceleration = acceleration; + this.deceleration = deceleration; + this.minWaitTicks = minWaitTicks; + } + + public double getEngage() { + return engage; + } + + public double getDriveSpeed() { + return driveSpeed; + } + + public boolean canSpawn() { + return canSpawn; + } + + public double getAcceleration() { + return acceleration; + } + + public double getDeceleration() { + return deceleration; + } + + public int getMinWaitTicks() { + return minWaitTicks; + } + + public static BlockSectionSpecConfig fromConfigurationSection(ConfigurationSection configurationSection) { + double engage = getDouble(configurationSection, "engage", 0.01); + double driveSpeed = getDouble(configurationSection, "driveSpeed", 1.0); + boolean canSpawn = getBoolean(configurationSection, "canSpawn", false); + double acceleration = getDouble(configurationSection, "acceleration", 0.1); + double deceleration = getDouble(configurationSection, "deceleration", acceleration); + int minWaitTicks = getInt(configurationSection, "minWaitTicks", 0); + + return new BlockSectionSpecConfig(engage, driveSpeed, canSpawn, acceleration, deceleration, minWaitTicks); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/BrakeSectionSpecConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/BrakeSectionSpecConfig.java new file mode 100644 index 00000000..8b02ed29 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/BrakeSectionSpecConfig.java @@ -0,0 +1,29 @@ +package com.jverbruggen.jrides.config.coaster.objects.section.ranged; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +public class BrakeSectionSpecConfig extends BaseConfig { + private final double driveSpeed; + private final double deceleration; + + public BrakeSectionSpecConfig(double driveSpeed, double deceleration) { + this.driveSpeed = driveSpeed; + this.deceleration = deceleration; + } + + public double getDriveSpeed() { + return driveSpeed; + } + + public double getDeceleration() { + return deceleration; + } + + public static BrakeSectionSpecConfig fromConfigurationSection(ConfigurationSection configurationSection) { + double driveSpeed = getDouble(configurationSection, "driveSpeed"); + double deceleration = getDouble(configurationSection, "deceleration"); + + return new BrakeSectionSpecConfig(driveSpeed, deceleration); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/CoasterStationConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/CoasterStationConfig.java new file mode 100644 index 00000000..e08d715a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/CoasterStationConfig.java @@ -0,0 +1,90 @@ +package com.jverbruggen.jrides.config.coaster.objects.section.ranged; + +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.config.gates.StationConfig; +import com.jverbruggen.jrides.control.DispatchLock; +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.effect.EffectTriggerFactory; +import com.jverbruggen.jrides.effect.handle.train.TrainEffectTriggerHandle; +import com.jverbruggen.jrides.models.properties.MinMaxWaitingTimer; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.ride.CoasterStationHandle; +import com.jverbruggen.jrides.models.ride.RideType; +import com.jverbruggen.jrides.models.ride.gate.Gate; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.List; + +import javax.annotation.Nonnull; + +public class CoasterStationConfig extends StationConfig { + private final boolean canSpawn; + private final double engage; + private final double driveSpeed; + private final int passThroughCount; + private final boolean forwardsDispatch; + + public CoasterStationConfig(double engage, double driveSpeed, int passThroughCount, boolean forwardsDispatch, int minimumWaitIntervalSeconds, int maximumWaitIntervalSeconds, StationEffectsConfig stationEffectsConfig, PlayerLocation ejectLocation, boolean canSpawn) { + super(minimumWaitIntervalSeconds, maximumWaitIntervalSeconds, stationEffectsConfig, ejectLocation); + this.engage = engage; + this.driveSpeed = driveSpeed; + this.passThroughCount = passThroughCount; + this.forwardsDispatch = forwardsDispatch; + this.canSpawn = canSpawn; + } + + public boolean canSpawn() { + return canSpawn; + } + + public double getEngage() { + return engage; + } + + public double getDriveSpeed() { + return driveSpeed; + } + + public int getPassThroughCount() { + return passThroughCount; + } + + public boolean isForwardsDispatch() { + return forwardsDispatch; + } + + public static CoasterStationConfig fromConfigurationSection(ConfigurationSection configurationSection) { + boolean canSpawn = getBoolean(configurationSection, "canSpawn", true); + double engage = getDouble(configurationSection, "engage", 0.5); + double driveSpeed = getDouble(configurationSection, "driveSpeed", 1.0); + int passThroughCount = getInt(configurationSection, "passThroughCount", 0); + boolean forwardsDispatch = getBoolean(configurationSection, "forwardsDispatch", true); + int minimumWaitIntervalSeconds = getInt(configurationSection, "minimumWaitIntervalSeconds", 0); + int maximumWaitIntervalSeconds = getInt(configurationSection, "maximumWaitIntervalSeconds", 60); + StationEffectsConfig effects = StationEffectsConfig.fromConfigurationSection(configurationSection.getConfigurationSection("effects")); + PlayerLocation ejectLocation = PlayerLocation.fromDoubleList(configurationSection.getDoubleList("ejectLocation")); + + return new CoasterStationConfig(engage, driveSpeed, passThroughCount, forwardsDispatch, minimumWaitIntervalSeconds, maximumWaitIntervalSeconds, effects, ejectLocation, canSpawn); + } + + public @Nonnull CoasterStationHandle createStationHandle(String stationName, String shortStationName, TriggerContext triggerContext, CoasterHandle coasterHandle, List gates, DispatchLock minimumWaitTimeDispatchLock){ + EffectTriggerFactory effectTriggerFactory = ServiceProvider.getSingleton(EffectTriggerFactory.class); + + String rideIdentifier = coasterHandle.getRide().getIdentifier(); + + StationEffectsConfig stationEffectsConfig = getStationEffectsConfig(); + List entryBlockingEffectTriggers = effectTriggerFactory.getFramelessEffectTriggers(RideType.COASTER, rideIdentifier, stationEffectsConfig.getEntryBlockingEffects()); + List exitBlockingEffectTriggers = effectTriggerFactory.getFramelessEffectTriggers(RideType.COASTER, rideIdentifier, stationEffectsConfig.getExitBlockingEffects()); + List exitEffectTriggers = effectTriggerFactory.getFramelessEffectTriggers(RideType.COASTER, rideIdentifier, stationEffectsConfig.getExitEffects()); + PlayerLocation ejectLocation = getEjectLocation(); + + MinMaxWaitingTimer waitingTimer = createWaitingTimer(minimumWaitTimeDispatchLock); + + CoasterStationHandle stationHandle = new CoasterStationHandle(coasterHandle, stationName, shortStationName, triggerContext, gates, waitingTimer, + entryBlockingEffectTriggers, exitBlockingEffectTriggers, exitEffectTriggers, ejectLocation); + triggerContext.setParentStation(stationHandle); + + return stationHandle; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/DriveAndReleaseSectionSpecConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/DriveAndReleaseSectionSpecConfig.java new file mode 100644 index 00000000..b452dbe3 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/DriveAndReleaseSectionSpecConfig.java @@ -0,0 +1,50 @@ +package com.jverbruggen.jrides.config.coaster.objects.section.ranged; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +public class DriveAndReleaseSectionSpecConfig extends BaseConfig { + private final double engage; + private final double driveSpeed; + private final double acceleration; + private final double deceleration; + private final int waitTicks; + + public DriveAndReleaseSectionSpecConfig(double engage, double driveSpeed, double acceleration, double deceleration, int waitTicks) { + this.engage = engage; + this.driveSpeed = driveSpeed; + this.acceleration = acceleration; + this.deceleration = deceleration; + this.waitTicks = waitTicks; + } + + public double getEngage() { + return engage; + } + + public double getDriveSpeed() { + return driveSpeed; + } + + public double getAcceleration() { + return acceleration; + } + + public double getDeceleration() { + return deceleration; + } + + public int getWaitTicks() { + return waitTicks; + } + + public static DriveAndReleaseSectionSpecConfig fromConfigurationSection(ConfigurationSection configurationSection) { + double driveSpeed = getDouble(configurationSection, "driveSpeed", 1.0); + double acceleration = getDouble(configurationSection, "acceleration", 1.0); + double deceleration = getDouble(configurationSection, "deceleration", acceleration); + double engage = getDouble(configurationSection, "engage", .5); + int waitTicks = getInt(configurationSection, "waitIntervalTicks", 1); + + return new DriveAndReleaseSectionSpecConfig(engage, driveSpeed, acceleration, deceleration, waitTicks); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/DriveSectionSpecConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/DriveSectionSpecConfig.java new file mode 100644 index 00000000..eebecc9f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/DriveSectionSpecConfig.java @@ -0,0 +1,43 @@ +package com.jverbruggen.jrides.config.coaster.objects.section.ranged; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +public class DriveSectionSpecConfig extends BaseConfig { + private final boolean ignoreDirection; + private final double driveSpeed; + private final double acceleration; + private final double deceleration; + + public DriveSectionSpecConfig(boolean ignoreDirection, double driveSpeed, double acceleration, double deceleration) { + this.ignoreDirection = ignoreDirection; + this.driveSpeed = driveSpeed; + this.acceleration = acceleration; + this.deceleration = deceleration; + } + + public boolean isIgnoreDirection() { + return ignoreDirection; + } + + public double getDriveSpeed() { + return driveSpeed; + } + + public double getAcceleration() { + return acceleration; + } + + public double getDeceleration() { + return deceleration; + } + + public static DriveSectionSpecConfig fromConfigurationSection(ConfigurationSection configurationSection) { + boolean ignoreDirection = getBoolean(configurationSection, "ignoreDirection", false); + double driveSpeed = getDouble(configurationSection, "driveSpeed", 1.0); + double acceleration = getDouble(configurationSection, "acceleration", 1.0); + double deceleration = getDouble(configurationSection, "deceleration", acceleration); + + return new DriveSectionSpecConfig(ignoreDirection, driveSpeed, acceleration, deceleration); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/DriveStopDriveSectionSpecConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/DriveStopDriveSectionSpecConfig.java new file mode 100644 index 00000000..38fcdd63 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/DriveStopDriveSectionSpecConfig.java @@ -0,0 +1,59 @@ +package com.jverbruggen.jrides.config.coaster.objects.section.ranged; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +public class DriveStopDriveSectionSpecConfig extends BaseConfig { + private final double engage; + private final double driveSpeedIn; + private final double driveSpeedOut; + private final double acceleration; + private final double deceleration; + private final int waitTicks; + + public DriveStopDriveSectionSpecConfig(double engage, double driveSpeedIn, double driveSpeedOut, double acceleration, double deceleration, int waitTicks) { + this.engage = engage; + this.driveSpeedIn = driveSpeedIn; + this.driveSpeedOut = driveSpeedOut; + this.acceleration = acceleration; + this.deceleration = deceleration; + this.waitTicks = waitTicks; + } + + public double getEngage() { + return engage; + } + + public double getDriveSpeedIn() { + return driveSpeedIn; + } + + public double getDriveSpeedOut() { + return driveSpeedOut; + } + + public double getAcceleration() { + return acceleration; + } + + public double getDeceleration() { + return deceleration; + } + + public int getWaitTicks() { + return waitTicks; + } + + public static DriveStopDriveSectionSpecConfig fromConfigurationSection(ConfigurationSection configurationSection) { + double defaultDriveSpeed = getDouble(configurationSection, "driveSpeed", 1.0); + + double driveSpeedIn = getDouble(configurationSection, "driveSpeedIn", defaultDriveSpeed); + double driveSpeedOut = getDouble(configurationSection, "driveSpeedOut", defaultDriveSpeed); + double acceleration = getDouble(configurationSection, "acceleration", 1.0); + double deceleration = getDouble(configurationSection, "deceleration", acceleration); + double engage = getDouble(configurationSection, "engage", .5); + int waitTicks = getInt(configurationSection, "waitIntervalTicks", 10); + + return new DriveStopDriveSectionSpecConfig(engage, driveSpeedIn, driveSpeedOut, acceleration, deceleration, waitTicks); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/LaunchEffectsConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/LaunchEffectsConfig.java new file mode 100644 index 00000000..cec26c87 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/LaunchEffectsConfig.java @@ -0,0 +1,26 @@ +package com.jverbruggen.jrides.config.coaster.objects.section.ranged; + +import org.bukkit.configuration.ConfigurationSection; + +import java.util.List; + +public class LaunchEffectsConfig { + private final List launchEffects; + + public LaunchEffectsConfig(List launchEffects) { + this.launchEffects = launchEffects; + } + + public List getLaunchEffects() { + return launchEffects; + } + + public static LaunchEffectsConfig fromConfigurationSection(ConfigurationSection configurationSection) { + if(configurationSection == null) return new LaunchEffectsConfig(List.of()); + + List launchEffects = configurationSection.getStringList("launch"); + + return new LaunchEffectsConfig(launchEffects); + } +} + diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/LaunchSectionSpecConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/LaunchSectionSpecConfig.java new file mode 100644 index 00000000..d0992d07 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/LaunchSectionSpecConfig.java @@ -0,0 +1,100 @@ +package com.jverbruggen.jrides.config.coaster.objects.section.ranged; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; +import org.checkerframework.checker.nullness.qual.NonNull; + +public class LaunchSectionSpecConfig extends BaseConfig { + private final boolean canSpawn; + private final double driveSpeed; + private final double acceleration; + private final double deceleration; + private final double engage; + private final int waitTicks; + private final boolean forwardsLaunch; + + private final double launchAcceleration; + private final double launchSpeed; + private final double launchSpeedBackward; + private final LaunchEffectsConfig launchEffectsConfig; + + public LaunchSectionSpecConfig(boolean canSpawn, double driveSpeed, double acceleration, double deceleration, double engage, int waitTicks, boolean forwardsLaunch, double launchAcceleration, double launchSpeed, double launchSpeedBackward, LaunchEffectsConfig launchEffectsConfig) { + this.canSpawn = canSpawn; + this.driveSpeed = driveSpeed; + this.acceleration = acceleration; + this.deceleration = deceleration; + this.engage = engage; + this.waitTicks = waitTicks; + this.forwardsLaunch = forwardsLaunch; + this.launchAcceleration = launchAcceleration; + this.launchSpeed = launchSpeed; + this.launchSpeedBackward = launchSpeedBackward; + this.launchEffectsConfig = launchEffectsConfig; + } + + public double getDriveSpeed() { + return driveSpeed; + } + + public double getAcceleration() { + return acceleration; + } + + public double getDeceleration() { + return deceleration; + } + + public double getEngage() { + return engage; + } + + public int getWaitTicks() { + return waitTicks; + } + + public boolean isForwardsLaunch() { + return forwardsLaunch; + } + + public double getLaunchAcceleration() { + return launchAcceleration; + } + + public double getLaunchSpeed() { + return launchSpeed; + } + + public double getLaunchSpeedBackward() { + return launchSpeedBackward; + } + + public boolean canSpawn() { + return canSpawn; + } + + @NonNull + public LaunchEffectsConfig getLaunchEffectsConfig() { + return launchEffectsConfig; + } + + public static LaunchSectionSpecConfig fromConfigurationSection(ConfigurationSection configurationSection) { + boolean canSpawn = getBoolean(configurationSection, "canSpawn", false); + double engage = getDouble(configurationSection, "engage", 0.0); + double driveSpeed = getDouble(configurationSection, "driveSpeed", 1.0); + double acceleration = getDouble(configurationSection, "acceleration", 0.1); + double deceleration = getDouble(configurationSection, "deceleration", acceleration); + int waitTicks = getInt(configurationSection, "waitIntervalTicks", -1); + double launchAcceleration = getDouble(configurationSection, "launchAcceleration", 0.1); + double launchSpeed = getDouble(configurationSection, "launchSpeed", 5.0); + double launchSpeedBackward = getDouble(configurationSection, "launchSpeedBackward", launchSpeed); + LaunchEffectsConfig launchEffectsConfig = LaunchEffectsConfig.fromConfigurationSection(configurationSection.getConfigurationSection("effects")); + boolean forwardsLaunch = getBoolean(configurationSection, "forwardsLaunch", true); + + if(launchSpeed <= 0) + throw new RuntimeException("launchSpeed should be bigger than 0"); + if(launchSpeedBackward <= 0) + throw new RuntimeException("launchSpeedBackward should be bigger than 0"); + + return new LaunchSectionSpecConfig(canSpawn, driveSpeed, acceleration, deceleration, engage, waitTicks, forwardsLaunch, launchAcceleration, launchSpeed, launchSpeedBackward, launchEffectsConfig); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/ProximityDriveSectionSpecConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/ProximityDriveSectionSpecConfig.java new file mode 100644 index 00000000..1e85cedb --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/ProximityDriveSectionSpecConfig.java @@ -0,0 +1,50 @@ +package com.jverbruggen.jrides.config.coaster.objects.section.ranged; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +public class ProximityDriveSectionSpecConfig extends BaseConfig { + private final boolean canSpawn; + private final double driveSpeed; + private final double acceleration; + private final double deceleration; + private final int minTrainDistance; + + public ProximityDriveSectionSpecConfig(boolean canSpawn, double driveSpeed, double acceleration, double deceleration, int minTrainDistance) { + this.canSpawn = canSpawn; + this.driveSpeed = driveSpeed; + this.acceleration = acceleration; + this.deceleration = deceleration; + this.minTrainDistance = minTrainDistance; + } + + public boolean canSpawn() { + return canSpawn; + } + + public double getDriveSpeed() { + return driveSpeed; + } + + public double getAcceleration() { + return acceleration; + } + + public double getDeceleration() { + return deceleration; + } + + public int getMinTrainDistance() { + return minTrainDistance; + } + + public static ProximityDriveSectionSpecConfig fromConfigurationSection(ConfigurationSection configurationSection) { + boolean canSpawn = getBoolean(configurationSection, "canSpawn", false); + double driveSpeed = getDouble(configurationSection, "driveSpeed", 1.0); + double acceleration = getDouble(configurationSection, "acceleration", 1.0); + double deceleration = getDouble(configurationSection, "deceleration", acceleration); + int minTrainDistance = getInt(configurationSection, "minTrainDistance", 50); + + return new ProximityDriveSectionSpecConfig(canSpawn, driveSpeed, acceleration, deceleration, minTrainDistance); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/StationEffectsConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/StationEffectsConfig.java new file mode 100644 index 00000000..b3c43096 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/StationEffectsConfig.java @@ -0,0 +1,46 @@ +package com.jverbruggen.jrides.config.coaster.objects.section.ranged; + +import org.bukkit.Bukkit; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.List; + +public class StationEffectsConfig { + private final List entryBlockingEffects; + private final List exitBlockingEffects; + private final List exitEffects; + + public StationEffectsConfig(List entryBlockingEffects, List exitBlockingEffects, List exitEffects) { + this.entryBlockingEffects = entryBlockingEffects; + this.exitBlockingEffects = exitBlockingEffects; + this.exitEffects = exitEffects; + } + + public StationEffectsConfig() { + this.entryBlockingEffects = null; + this.exitBlockingEffects = null; + this.exitEffects = null; + } + + public List getEntryBlockingEffects() { + return entryBlockingEffects; + } + + public List getExitBlockingEffects() { + return exitBlockingEffects; + } + + public List getExitEffects() { + return exitEffects; + } + + public static StationEffectsConfig fromConfigurationSection(ConfigurationSection configurationSection) { + if(configurationSection == null) return new StationEffectsConfig(); + List entryBlockingEffects = configurationSection.getStringList("entryBlocking"); + List exitBlockingEffects = configurationSection.getStringList("exitBlocking"); + List exitEffects = configurationSection.getStringList("exit"); + + return new StationEffectsConfig(entryBlockingEffects, exitBlockingEffects, exitEffects); + } +} + diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/StorageSectionSpecConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/StorageSectionSpecConfig.java new file mode 100644 index 00000000..8ca9156c --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/StorageSectionSpecConfig.java @@ -0,0 +1,18 @@ +package com.jverbruggen.jrides.config.coaster.objects.section.ranged; + +import org.bukkit.configuration.ConfigurationSection; + +public class StorageSectionSpecConfig { + @SuppressWarnings("unused") + private final String sectionAtEnd; + + public StorageSectionSpecConfig(String sectionAtEnd) { + this.sectionAtEnd = sectionAtEnd; + } + + public static StorageSectionSpecConfig fromConfigurationSection(ConfigurationSection configurationSection) { + String sectionAtEnd = configurationSection.getString("sectionAtEnd"); + + return new StorageSectionSpecConfig(sectionAtEnd); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/TrimBrakeSectionSpecConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/TrimBrakeSectionSpecConfig.java new file mode 100644 index 00000000..7c2da08a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/TrimBrakeSectionSpecConfig.java @@ -0,0 +1,22 @@ +package com.jverbruggen.jrides.config.coaster.objects.section.ranged; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +public class TrimBrakeSectionSpecConfig extends BaseConfig { + private final double trimResistanceConstant; + + public TrimBrakeSectionSpecConfig(double trimResistanceConstant) { + this.trimResistanceConstant = trimResistanceConstant; + } + + public double getTrimResistanceConstant() { + return trimResistanceConstant; + } + + public static TrimBrakeSectionSpecConfig fromConfigurationSection(ConfigurationSection configurationSection) { + double trimResistanceConstant = getDouble(configurationSection, "trimResistanceConstant", 0.9); + + return new TrimBrakeSectionSpecConfig(trimResistanceConstant); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/transfer/TransferSectionPositionSpecConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/transfer/TransferSectionPositionSpecConfig.java new file mode 100644 index 00000000..7677ef60 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/transfer/TransferSectionPositionSpecConfig.java @@ -0,0 +1,96 @@ +package com.jverbruggen.jrides.config.coaster.objects.section.ranged.transfer; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.models.math.Vector3; +import org.bukkit.configuration.ConfigurationSection; + +public class TransferSectionPositionSpecConfig extends BaseConfig { + private final String sectionAtStart; + private final String sectionAtEnd; + private final boolean sectionAtStartForwards; + private final boolean sectionAtEndForwards; + private final boolean sectionAtStartConnectsToStart; + private final boolean sectionAtEndConnectsToStart; + private final Vector3 position; + private final Vector3 rotation; + private final int moveTicks; + + public TransferSectionPositionSpecConfig(String sectionAtStart, String sectionAtEnd, boolean sectionAtStartForwards, boolean sectionAtEndForwards, boolean sectionAtStartConnectsToStart, boolean sectionAtEndConnectsToStart, Vector3 position, Vector3 rotation, int moveTicks) { + this.sectionAtStart = sectionAtStart; + this.sectionAtEnd = sectionAtEnd; + this.sectionAtStartForwards = sectionAtStartForwards; + this.sectionAtEndForwards = sectionAtEndForwards; + this.sectionAtStartConnectsToStart = sectionAtStartConnectsToStart; + this.sectionAtEndConnectsToStart = sectionAtEndConnectsToStart; + this.position = position; + this.rotation = rotation; + this.moveTicks = moveTicks; + } + + public String getSectionAtStart() { + return sectionAtStart; + } + + public String getSectionAtEnd() { + return sectionAtEnd; + } + + public boolean isSectionAtStartConnectsToStart() { + return sectionAtStartConnectsToStart; + } + + public boolean isSectionAtEndConnectsToStart() { + return sectionAtEndConnectsToStart; + } + + public boolean isSectionAtStartForwards() { + return sectionAtStartForwards; + } + + public boolean isSectionAtEndForwards() { + return sectionAtEndForwards; + } + + public Vector3 getPosition() { + return position; + } + + public Vector3 getRotation() { + return rotation; + } + + public int getMoveTicks() { + return moveTicks; + } + + @Override + public String toString() { + return "Transfer position of " + getPosition() + " ticks " + getMoveTicks(); + } + + public static TransferSectionPositionSpecConfig fromConfigurationSection(ConfigurationSection configurationSection) { + String sectionAtStart = configurationSection.getString("sectionAtStart"); + String sectionAtEnd = configurationSection.getString("sectionAtEnd"); + boolean sectionAtStartForwards = getBoolean(configurationSection, "sectionAtStartForwards", false); + boolean sectionAtEndForwards = getBoolean(configurationSection, "sectionAtEndForwards", true); + boolean sectionAtStartConnectsToStart = getBoolean(configurationSection, "sectionAtStartConnectsToStart", false); + boolean sectionAtEndConnectsToStart = getBoolean(configurationSection, "sectionAtEndConnectsToStart", true); + + int moveTicks; + if(configurationSection.contains("moveTicks")) + moveTicks = configurationSection.getInt("moveTicks"); + else moveTicks = 0; + + Vector3 position; + if(configurationSection.contains("position")) + position = Vector3.fromDoubleList(configurationSection.getDoubleList("position")); + else position = new Vector3(0,0,0); + + Vector3 rotation; + if(configurationSection.contains("rotation")) + rotation = Vector3.fromDoubleList(configurationSection.getDoubleList("rotation")); + else rotation = new Vector3(0,0,0); + + return new TransferSectionPositionSpecConfig(sectionAtStart, sectionAtEnd, sectionAtStartForwards, sectionAtEndForwards, sectionAtStartConnectsToStart, sectionAtEndConnectsToStart, position, rotation, moveTicks); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/transfer/TransferSectionSpecConfig.java b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/transfer/TransferSectionSpecConfig.java new file mode 100644 index 00000000..66d309c5 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/coaster/objects/section/ranged/transfer/TransferSectionSpecConfig.java @@ -0,0 +1,92 @@ +package com.jverbruggen.jrides.config.coaster.objects.section.ranged.transfer; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.models.math.Vector3; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +public class TransferSectionSpecConfig extends BaseConfig { + private final List positions; + private final double engage; + private final double enterDriveSpeed; + private final double exitDriveSpeed; + private final double acceleration; + private final double deceleration; + private final Vector3 origin; + private final Vector3 modelOffsetPosition; + private final Vector3 modelOffsetRotation; + + public TransferSectionSpecConfig(List positions, double engage, double enterDriveSpeed, double exitDriveSpeed, double acceleration, double deceleration, Vector3 origin, Vector3 modelOffsetPosition, Vector3 modelOffsetRotation) { + this.positions = positions; + this.engage = engage; + this.enterDriveSpeed = enterDriveSpeed; + this.exitDriveSpeed = exitDriveSpeed; + this.acceleration = acceleration; + this.deceleration = deceleration; + this.origin = origin; + this.modelOffsetPosition = modelOffsetPosition; + this.modelOffsetRotation = modelOffsetRotation; + } + + public List getPositions() { + return positions; + } + + public double getEngage() { + return engage; + } + + public double getEnterDriveSpeed() { + return enterDriveSpeed; + } + + public double getExitDriveSpeed() { + return exitDriveSpeed; + } + + public double getAcceleration() { + return acceleration; + } + + public double getDeceleration() { + return deceleration; + } + + public Vector3 getOrigin() { + return origin; + } + + public Vector3 getModelOffsetPosition() { + return modelOffsetPosition; + } + + public Vector3 getModelOffsetRotation() { + return modelOffsetRotation; + } + + public static TransferSectionSpecConfig fromConfigurationSection(ConfigurationSection configurationSection){ + List positions = new ArrayList<>(); + + ConfigurationSection positionsConfigurationSection = configurationSection.getConfigurationSection("positions"); + Set positionsStrings = positionsConfigurationSection.getKeys(false); + for(String positionsString : positionsStrings){ + ConfigurationSection positionConfigurationSection = positionsConfigurationSection.getConfigurationSection(positionsString); + TransferSectionPositionSpecConfig transferPosition = TransferSectionPositionSpecConfig.fromConfigurationSection(positionConfigurationSection); + positions.add(transferPosition); + } + + double engage = getDouble(configurationSection, "engage", 0.5); + double enterDriveSpeed = getDouble(configurationSection, "enterDriveSpeed", 0.5); + double exitDriveSpeed = getDouble(configurationSection, "exitDriveSpeed", enterDriveSpeed); + double acceleration = getDouble(configurationSection, "acceleration", 0.1); + double deceleration = getDouble(configurationSection, "deceleration", acceleration); + Vector3 origin = Vector3.fromDoubleList(getDoubleList(configurationSection, "origin")); + Vector3 modelOffsetPosition = Vector3.fromDoubleList(getDoubleList(configurationSection, "modelOffsetPosition")); + Vector3 modelOffsetRotation = Vector3.fromDoubleList(getDoubleList(configurationSection, "modelOffsetRotation")); + + return new TransferSectionSpecConfig(positions, engage, enterDriveSpeed, exitDriveSpeed, acceleration, deceleration, origin, modelOffsetPosition, modelOffsetRotation); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/FlatRideConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/FlatRideConfig.java new file mode 100644 index 00000000..f789e8c3 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/FlatRideConfig.java @@ -0,0 +1,76 @@ +package com.jverbruggen.jrides.config.flatride; + +import com.jverbruggen.jrides.config.coaster.objects.InteractionEntitiesConfig; +import com.jverbruggen.jrides.config.coaster.objects.SoundsConfig; +import com.jverbruggen.jrides.config.coaster.objects.item.ItemStackConfig; +import com.jverbruggen.jrides.config.flatride.structure.StructureConfig; +import com.jverbruggen.jrides.config.flatride.timing.TimingConfig; +import com.jverbruggen.jrides.config.gates.GatesConfig; +import com.jverbruggen.jrides.config.gates.StationConfig; +import com.jverbruggen.jrides.config.ride.AbstractRideConfig; +import com.jverbruggen.jrides.config.ride.RideCounterMapConfigs; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import org.bukkit.ChatColor; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +public class FlatRideConfig extends AbstractRideConfig { + private final StationConfig stationConfig; + private final StructureConfig structureConfig; + private final TimingConfig timingConfig; + + public FlatRideConfig(String manifestVersion, String identifier, String displayName, List displayDescription, ItemStackConfig displayItem, + PlayerLocation warpLocation, PlayerLocation customEjectLocation, GatesConfig gates, InteractionEntitiesConfig interactionEntities, + boolean canExitDuringRide, StationConfig stationConfig, SoundsConfig soundsConfig, StructureConfig structureConfig, + TimingConfig timingConfig, RideCounterMapConfigs rideCounterMapConfigs, boolean debugMode) { + super(manifestVersion, identifier, displayName, displayDescription, displayItem, warpLocation, customEjectLocation, gates, soundsConfig, canExitDuringRide, interactionEntities, rideCounterMapConfigs, debugMode); + this.stationConfig = stationConfig; + this.structureConfig = structureConfig; + this.timingConfig = timingConfig; + } + + public StructureConfig getStructureConfig() { + return structureConfig; + } + + public TimingConfig getTimingConfig() { + return timingConfig; + } + + public StationConfig getStationConfig() { + return stationConfig; + } + + public static FlatRideConfig fromConfigurationSection(ConfigurationSection configurationSection) { + String manifestVersion = configurationSection.getString("manifestVersion"); + String identifier = configurationSection.getString("identifier"); + String displayName = configurationSection.getString("displayName"); + + List displayDescription = Arrays.stream(getString(configurationSection, "displayDescription", "").split("\\\\n")) + .map(d -> ChatColor.GRAY + d) + .collect(Collectors.toList()); + if(displayDescription.size() == 1 && ChatColor.stripColor(displayDescription.get(0)).equals("")) + displayDescription.clear(); + + ItemStackConfig displayItem = ItemStackConfig.fromConfigurationSection(configurationSection.getConfigurationSection("displayItem")); + PlayerLocation warpLocation = PlayerLocation.fromDoubleList(configurationSection.getDoubleList("warpLocation")); + PlayerLocation customEjectLocation = PlayerLocation.fromDoubleList(getDoubleList(configurationSection, "customEjectLocation", null)); + GatesConfig gates = GatesConfig.fromConfigurationSection(configurationSection.getConfigurationSection("gates")); + SoundsConfig sounds = SoundsConfig.fromConfigurationSection(configurationSection.getConfigurationSection("sounds")); + boolean canExitDuringRide = getBoolean(configurationSection, "canExitDuringRide", false); + InteractionEntitiesConfig interactionEntities = InteractionEntitiesConfig.fromConfigurationSection(getConfigurationSection(configurationSection, "interactionEntities")); + StationConfig stationConfig = StationConfig.fromConfigurationSection(getConfigurationSection(configurationSection, "station")); + StructureConfig structureConfig = StructureConfig.fromConfigurationSection(Objects.requireNonNull(getConfigurationSection(configurationSection, "structure"), "Structure for flatride not present")); + TimingConfig timingConfig = TimingConfig.fromConfigurationSection(getConfigurationSection(configurationSection, "timing")); + RideCounterMapConfigs rideCounterMapConfigs = RideCounterMapConfigs.fromConfigurationSection(identifier, getConfigurationSection(configurationSection, "rideCounterMaps")); + boolean debugMode = getBoolean(configurationSection, "debugMode", false); + + return new FlatRideConfig(manifestVersion, identifier, displayName, displayDescription, displayItem, warpLocation, + customEjectLocation, gates, interactionEntities, canExitDuringRide, stationConfig, sounds, structureConfig, + timingConfig, rideCounterMapConfigs, debugMode); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/AbstractStructureConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/AbstractStructureConfig.java new file mode 100644 index 00000000..93515933 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/AbstractStructureConfig.java @@ -0,0 +1,38 @@ +package com.jverbruggen.jrides.config.flatride.structure; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.config.coaster.objects.cart.ModelConfig; +import com.jverbruggen.jrides.config.flatride.structure.attachment.AttachmentConfig; + +import java.util.List; + +public abstract class AbstractStructureConfig extends BaseConfig implements StructureConfigItem { + private final String identifier; + private final boolean root; + private final List flatRideModels; + private final AttachmentConfig attachmentConfig; + + public AbstractStructureConfig(String identifier, boolean root, List flatRideModels, AttachmentConfig attachmentConfig) { + this.identifier = identifier; + this.root = root; + this.flatRideModels = flatRideModels; + this.attachmentConfig = attachmentConfig; + } + + @Override + public String getIdentifier() { + return identifier; + } + + public boolean isRoot() { + return root; + } + + public AttachmentConfig getAttachmentConfig() { + return attachmentConfig; + } + + public List getFlatRideModels() { + return flatRideModels; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/ControlConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/ControlConfig.java new file mode 100644 index 00000000..a3690c10 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/ControlConfig.java @@ -0,0 +1,7 @@ +package com.jverbruggen.jrides.config.flatride.structure; + +import com.jverbruggen.jrides.models.ride.flatride.PlayerControl; + +public interface ControlConfig { + PlayerControl createPlayerControl(); +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/StructureConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/StructureConfig.java new file mode 100644 index 00000000..8bed41e7 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/StructureConfig.java @@ -0,0 +1,50 @@ +package com.jverbruggen.jrides.config.flatride.structure; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.LimbConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.LinearActuatorConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.RotorConfig; +import com.jverbruggen.jrides.config.flatride.structure.basic.StaticStructureConfig; +import com.jverbruggen.jrides.config.flatride.structure.seat.SeatConfig; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +public class StructureConfig extends BaseConfig { + private final List items; + + public StructureConfig(List items) { + this.items = items; + } + + public List getItems() { + return items; + } + + public static StructureConfig fromConfigurationSection(ConfigurationSection configurationSection) { + List items = new ArrayList<>(); + + Set keys = configurationSection.getKeys(false); + for(String key : keys){ + ConfigurationSection itemConfigurationSection = getConfigurationSection(configurationSection, key); + if(itemConfigurationSection == null) throw new RuntimeException("No contents in structure item " + key); + + String type = getString(itemConfigurationSection, "type"); + + StructureConfigItem structureConfigItem = switch (type) { + case "static" -> StaticStructureConfig.fromConfigurationSection(itemConfigurationSection, key); + case "limb" -> LimbConfig.fromConfigurationSection(itemConfigurationSection, key); + case "rotor" -> RotorConfig.fromConfigurationSection(itemConfigurationSection, key); + case "seat" -> SeatConfig.fromConfigurationSection(itemConfigurationSection, key); + case "linear_actuator" -> LinearActuatorConfig.fromConfigurationSection(itemConfigurationSection, key); + default -> throw new RuntimeException("Unknown structure type '" + type + "'"); + }; + + items.add(structureConfigItem); + } + + return new StructureConfig(items); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/StructureConfigItem.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/StructureConfigItem.java new file mode 100644 index 00000000..98613c6f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/StructureConfigItem.java @@ -0,0 +1,11 @@ +package com.jverbruggen.jrides.config.flatride.structure; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; + +import java.util.List; + +public interface StructureConfigItem { + String getIdentifier(); + void createAndAddTo(List components, FlatRideHandle rideHandle); +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/AbstractActuatorConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/AbstractActuatorConfig.java new file mode 100644 index 00000000..95820f62 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/AbstractActuatorConfig.java @@ -0,0 +1,21 @@ +package com.jverbruggen.jrides.config.flatride.structure.actuator; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponentSpeed; +import com.jverbruggen.jrides.config.coaster.objects.cart.ModelConfig; +import com.jverbruggen.jrides.config.flatride.structure.AbstractStructureConfig; +import com.jverbruggen.jrides.config.flatride.structure.attachment.AttachmentConfig; + +import java.util.List; + +public abstract class AbstractActuatorConfig extends AbstractStructureConfig { + private final FlatRideComponentSpeed flatRideComponentSpeed; + + public AbstractActuatorConfig(String identifier, boolean root, AttachmentConfig attachmentConfig, FlatRideComponentSpeed flatRideComponentSpeed, List flatRideModels) { + super(identifier, root, flatRideModels, attachmentConfig); + this.flatRideComponentSpeed = flatRideComponentSpeed; + } + + public FlatRideComponentSpeed getFlatRideComponentSpeed() { + return flatRideComponentSpeed; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/LimbConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/LimbConfig.java new file mode 100644 index 00000000..07e77511 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/LimbConfig.java @@ -0,0 +1,52 @@ +package com.jverbruggen.jrides.config.flatride.structure.actuator; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.config.coaster.objects.cart.ModelConfig; +import com.jverbruggen.jrides.config.flatride.structure.AbstractStructureConfig; +import com.jverbruggen.jrides.config.flatride.structure.StructureConfigItem; +import com.jverbruggen.jrides.config.flatride.structure.attachment.AttachmentConfig; +import com.jverbruggen.jrides.config.flatride.structure.attachment.FixedAttachmentConfig; +import com.jverbruggen.jrides.config.flatride.structure.attachment.RelativeMultipleAttachmentConfig; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.ArrayList; +import java.util.List; + +public class LimbConfig extends AbstractStructureConfig { + private final String preloadAnim; + + public LimbConfig(String identifier, boolean root, AttachmentConfig attachmentConfig, List flatRideModelsConfig, String preloadAnim) { + super(identifier, root, flatRideModelsConfig, attachmentConfig); + this.preloadAnim = preloadAnim; + } + + @Override + public void createAndAddTo(List components, FlatRideHandle rideHandle) { + getAttachmentConfig().createLimb(this, components, rideHandle, preloadAnim); + } + + public static StructureConfigItem fromConfigurationSection(ConfigurationSection configurationSection, String identifier) { + boolean root = getBoolean(configurationSection, "root", false); + + AttachmentConfig attachmentConfig = null; + if(configurationSection.contains("position")){ + attachmentConfig = FixedAttachmentConfig.fromConfigurationSection(configurationSection); + } + if(configurationSection.contains("arm")){ + if(attachmentConfig != null) throw new RuntimeException("Can only create one attachment type for a linear actuator"); + attachmentConfig = RelativeMultipleAttachmentConfig.fromConfigurationSection(configurationSection); + } + + if(attachmentConfig == null) throw new RuntimeException("No attachment specified for linear actuator"); + + List modelConfigs; + if(configurationSection.contains("models")) + modelConfigs = ModelConfig.multipleFromConfigurationSection(getConfigurationSection(configurationSection, "models")); + else modelConfigs = new ArrayList<>(); + + String preloadAnim = getString(configurationSection, "preloadAnim", null); + + return new LimbConfig(identifier, root, attachmentConfig, modelConfigs, preloadAnim); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/LinearActuatorConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/LinearActuatorConfig.java new file mode 100644 index 00000000..d7979d50 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/LinearActuatorConfig.java @@ -0,0 +1,82 @@ +package com.jverbruggen.jrides.config.flatride.structure.actuator; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideComponentSpeed; +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.animator.flatride.linearactuator.mode.LinearActuatorModeEnum; +import com.jverbruggen.jrides.config.coaster.objects.cart.ModelConfig; +import com.jverbruggen.jrides.config.flatride.structure.StructureConfigItem; +import com.jverbruggen.jrides.config.flatride.structure.actuator.linearactuator.LinearActuatorTypeConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.linearactuator.ContinuousLinearActuatorConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.linearactuator.SineLinearActuatorConfig; +import com.jverbruggen.jrides.config.flatride.structure.attachment.AttachmentConfig; +import com.jverbruggen.jrides.config.flatride.structure.attachment.FixedAttachmentConfig; +import com.jverbruggen.jrides.config.flatride.structure.attachment.RelativeMultipleAttachmentConfig; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.ArrayList; +import java.util.List; + +public class LinearActuatorConfig extends AbstractActuatorConfig{ + private final String axis; + private final LinearActuatorTypeConfig linearActuatorTypeConfig; + + public LinearActuatorConfig(String identifier, boolean root, String axis, AttachmentConfig attachmentConfig, FlatRideComponentSpeed flatRideComponentSpeed, List flatRideModelsConfig, LinearActuatorTypeConfig linearActuatorTypeConfig) { + super(identifier, root, attachmentConfig, flatRideComponentSpeed, flatRideModelsConfig); + this.axis = axis; + this.linearActuatorTypeConfig = linearActuatorTypeConfig; + } + + public String getAxis() { + return axis; + } + + public LinearActuatorTypeConfig getLinearActuatorTypeConfig() { + return linearActuatorTypeConfig; + } + + @Override + public void createAndAddTo(List components, FlatRideHandle rideHandle) { + getAttachmentConfig().createLinearActuator(this, components, rideHandle); + } + + public static StructureConfigItem fromConfigurationSection(ConfigurationSection configurationSection, String identifier) { + boolean root = getBoolean(configurationSection, "root", false); + String axis = getString(configurationSection, "axis", "y"); + String mode = getString(configurationSection, "mode", "continuous"); + + LinearActuatorTypeConfig linearActuatorTypeConfig = switch (LinearActuatorModeEnum.from(mode)){ + case SINE -> SineLinearActuatorConfig.fromConfigurationSection(configurationSection); + case CONTINUOUS -> ContinuousLinearActuatorConfig.fromConfigurationSection(configurationSection); + }; + + AttachmentConfig attachmentConfig = null; + if(configurationSection.contains("position")){ + attachmentConfig = FixedAttachmentConfig.fromConfigurationSection(configurationSection); + } + if(configurationSection.contains("arm")){ + if(attachmentConfig != null) throw new RuntimeException("Can only create one attachment type for a linear actuator"); + attachmentConfig = RelativeMultipleAttachmentConfig.fromConfigurationSection(configurationSection); + } + + if(attachmentConfig == null) throw new RuntimeException("No attachment specified for linear actuator"); + + FlatRideComponentSpeed flatRideComponentSpeed; + if(configurationSection.contains("minSpeed")) { + flatRideComponentSpeed = new FlatRideComponentSpeed( + (float) getDouble(configurationSection, "speed"), + (float) getDouble(configurationSection, "minSpeed"), + (float) getDouble(configurationSection, "maxSpeed")); + }else{ + flatRideComponentSpeed = new FlatRideComponentSpeed( + (float)getDouble(configurationSection, "speed", 0)); + } + + List modelConfigs; + if(configurationSection.contains("models")) + modelConfigs = ModelConfig.multipleFromConfigurationSection(getConfigurationSection(configurationSection, "models")); + else modelConfigs = new ArrayList<>(); + + return new LinearActuatorConfig(identifier, root, axis, attachmentConfig, flatRideComponentSpeed, modelConfigs, linearActuatorTypeConfig); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/RotorConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/RotorConfig.java new file mode 100644 index 00000000..600455f5 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/RotorConfig.java @@ -0,0 +1,89 @@ +package com.jverbruggen.jrides.config.flatride.structure.actuator; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideComponentSpeed; +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.animator.flatride.rotor.mode.RotorModeEnum; +import com.jverbruggen.jrides.config.coaster.objects.cart.ModelConfig; +import com.jverbruggen.jrides.config.flatride.structure.StructureConfigItem; +import com.jverbruggen.jrides.config.flatride.structure.actuator.rotor.ContinuousRotorConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.rotor.RotorTypeConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.rotor.SineRotorConfig; +import com.jverbruggen.jrides.config.flatride.structure.attachment.AttachmentConfig; +import com.jverbruggen.jrides.config.flatride.structure.attachment.FixedAttachmentConfig; +import com.jverbruggen.jrides.config.flatride.structure.attachment.RelativeMultipleAttachmentConfig; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.ArrayList; +import java.util.List; + +public class RotorConfig extends AbstractActuatorConfig { + private final String rotorAxis; + private final RotorPlayerControlConfig playerControlConfig; + private final RotorTypeConfig rotorTypeConfig; + + + public RotorConfig(String identifier, boolean root, String rotorAxis, RotorPlayerControlConfig playerControlConfig, FlatRideComponentSpeed flatRideComponentSpeed, AttachmentConfig attachmentConfig, List flatRideModels, RotorTypeConfig rotorTypeConfig) { + super(identifier, root, attachmentConfig, flatRideComponentSpeed, flatRideModels); + this.rotorAxis = rotorAxis; + this.playerControlConfig = playerControlConfig; + this.rotorTypeConfig = rotorTypeConfig; + } + + @Override + public void createAndAddTo(List components, FlatRideHandle rideHandle) { + getAttachmentConfig().createRotorWithAttachment(this, components, rideHandle); + } + + public String getRotorAxis() { + return rotorAxis; + } + + public RotorTypeConfig getRotorTypeConfig() { + return rotorTypeConfig; + } + + public RotorPlayerControlConfig getPlayerControlConfig() { + return playerControlConfig; + } + + public static StructureConfigItem fromConfigurationSection(ConfigurationSection configurationSection, String identifier) { + boolean root = getBoolean(configurationSection, "root", false); + String axis = getString(configurationSection, "axis", "y"); + RotorPlayerControlConfig playerControlConfig = RotorPlayerControlConfig.fromConfigurationSection(identifier, configurationSection.getConfigurationSection("control")); + String mode = getString(configurationSection, "mode", "continuous"); + + RotorTypeConfig rotorTypeConfig = switch (RotorModeEnum.from(mode)){ + case SINE -> SineRotorConfig.fromConfigurationSection(configurationSection); + case CONTINUOUS -> ContinuousRotorConfig.fromConfigurationSection(configurationSection); + }; + + AttachmentConfig attachmentConfig = null; + if(configurationSection.contains("position")){ + attachmentConfig = FixedAttachmentConfig.fromConfigurationSection(configurationSection); + } + if(configurationSection.contains("arm")){ + if(attachmentConfig != null) throw new RuntimeException("Can only create one attachment type for a rotor"); + attachmentConfig = RelativeMultipleAttachmentConfig.fromConfigurationSection(configurationSection); + } + + if(attachmentConfig == null) throw new RuntimeException("No attachment specified for rotor"); + + FlatRideComponentSpeed flatRideComponentSpeed; + if(configurationSection.contains("maxSpeed") || configurationSection.contains("minSpeed")){ + flatRideComponentSpeed = new FlatRideComponentSpeed( + (float)getDouble(configurationSection, "speed"), + (float)getDouble(configurationSection, "minSpeed"), + (float)getDouble(configurationSection, "maxSpeed")); + }else{ + flatRideComponentSpeed = new FlatRideComponentSpeed((float)getDouble(configurationSection, "speed", 1)); + } + + List modelConfigs; + if(configurationSection.contains("models")) + modelConfigs = ModelConfig.multipleFromConfigurationSection(getConfigurationSection(configurationSection, "models")); + else modelConfigs = new ArrayList<>(); + + return new RotorConfig(identifier, root, axis, playerControlConfig, flatRideComponentSpeed, attachmentConfig, modelConfigs, rotorTypeConfig); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/RotorPlayerControlConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/RotorPlayerControlConfig.java new file mode 100644 index 00000000..6051e535 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/RotorPlayerControlConfig.java @@ -0,0 +1,79 @@ +package com.jverbruggen.jrides.config.flatride.structure.actuator; + +import com.jverbruggen.jrides.animator.flatride.rotor.RotorPlayerControl; +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.config.flatride.structure.ControlConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.playercontrol.PlayerControlConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.playercontrol.SpeedControlConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.playercontrol.TowardsPositionControlConfig; +import com.jverbruggen.jrides.models.math.MathUtil; +import org.bukkit.configuration.ConfigurationSection; + +import javax.annotation.Nullable; +import java.util.List; + +public class RotorPlayerControlConfig extends BaseConfig implements ControlConfig { + public final String type; + public final PlayerControlConfig playerControlConfig; + public final float accelerate; + public final String accumulator; + + public RotorPlayerControlConfig(String type, PlayerControlConfig playerControlConfig, float accelerate, String accumulator) { + this.type = type; + this.playerControlConfig = playerControlConfig; + this.accelerate = accelerate; + this.accumulator = accumulator; + } + + public String getType() { + return type; + } + + public static RotorPlayerControlConfig fromConfigurationSection(String identifier, @Nullable ConfigurationSection configurationSection) { + if(configurationSection == null) return null; + + String type = getString(configurationSection, "type"); + List speed = getDoubleList(configurationSection, "speed", List.of(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY)); + List position = getDoubleList(configurationSection, "position", List.of(Double.NEGATIVE_INFINITY, Double.NEGATIVE_INFINITY)); + float accelerate = (float)getDouble(configurationSection, "accelerate"); + String accumulator = getString(configurationSection, "accumulator"); + + if(speed.size() != 2) + throw new RuntimeException("Only supports rotor control config with speed of length 2! [, ] i.e. [-1, 1]"); + if(position.size() != 2) + throw new RuntimeException("Only supports rotor control config with position of length 2! [, ] i.e. [0, 45]"); + + float lowerSpeed = speed.get(0).floatValue(); + float upperSpeed = speed.get(1).floatValue(); + float lowerPosition = position.get(0).floatValue(); + float upperPosition = position.get(1).floatValue(); + + PlayerControlConfig playerControlConfig = null; + if(lowerSpeed != Float.NEGATIVE_INFINITY){ + playerControlConfig = new SpeedControlConfig(lowerSpeed, upperSpeed, accelerate); + } + if(lowerPosition != Float.NEGATIVE_INFINITY){ + if(playerControlConfig != null) + throw new RuntimeException("Rotor control config in '" + identifier + "' can only contain either one of position or speed, not both!"); + + playerControlConfig = new TowardsPositionControlConfig(MathUtil.floorMod(lowerPosition, 360), MathUtil.floorMod(upperPosition, 360), accelerate); + } + + return new RotorPlayerControlConfig( + type, playerControlConfig, Math.abs(accelerate), accumulator + ); + } + + @Override + public RotorPlayerControl createPlayerControl() { + if(type.equalsIgnoreCase("space_bar_control")){ + return playerControlConfig.createSpaceBarPlayerControl(); + }else if(type.equalsIgnoreCase("w_s_control")){ + return playerControlConfig.createWSPlayerControl(); + }else if(type.equalsIgnoreCase("a_d_control")){ + return playerControlConfig.createADPlayerControl(); + } + + throw new RuntimeException("Unknown player control type '" + type + "'"); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/linearactuator/ContinuousLinearActuatorConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/linearactuator/ContinuousLinearActuatorConfig.java new file mode 100644 index 00000000..b61083a9 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/linearactuator/ContinuousLinearActuatorConfig.java @@ -0,0 +1,27 @@ +package com.jverbruggen.jrides.config.flatride.structure.actuator.linearactuator; + +import com.jverbruggen.jrides.animator.flatride.linearactuator.mode.ContinuousMode; +import com.jverbruggen.jrides.animator.flatride.linearactuator.mode.LinearActuatorMode; +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +public class ContinuousLinearActuatorConfig extends BaseConfig implements LinearActuatorTypeConfig { + private final Double lowerBound; + private final Double upperBound; + + public ContinuousLinearActuatorConfig(Double lowerBound, Double upperBound) { + this.lowerBound = lowerBound; + this.upperBound = upperBound; + } + + @Override + public LinearActuatorMode createActuatorMode() { + return new ContinuousMode(lowerBound, upperBound); + } + + public static ContinuousLinearActuatorConfig fromConfigurationSection(ConfigurationSection configurationSection) { + Double lowerBound = getDoubleObj(configurationSection, "lowerBound", null); + Double upperBound = getDoubleObj(configurationSection, "upperBound", null); + return new ContinuousLinearActuatorConfig(lowerBound, upperBound); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/linearactuator/LinearActuatorTypeConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/linearactuator/LinearActuatorTypeConfig.java new file mode 100644 index 00000000..05b8cee8 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/linearactuator/LinearActuatorTypeConfig.java @@ -0,0 +1,7 @@ +package com.jverbruggen.jrides.config.flatride.structure.actuator.linearactuator; + +import com.jverbruggen.jrides.animator.flatride.linearactuator.mode.LinearActuatorMode; + +public interface LinearActuatorTypeConfig { + LinearActuatorMode createActuatorMode(); +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/linearactuator/SineLinearActuatorConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/linearactuator/SineLinearActuatorConfig.java new file mode 100644 index 00000000..16212d7c --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/linearactuator/SineLinearActuatorConfig.java @@ -0,0 +1,30 @@ +package com.jverbruggen.jrides.config.flatride.structure.actuator.linearactuator; + +import com.jverbruggen.jrides.animator.flatride.linearactuator.mode.LinearActuatorMode; +import com.jverbruggen.jrides.animator.flatride.linearactuator.mode.SineMode; +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.function.Supplier; + +public class SineLinearActuatorConfig extends BaseConfig implements LinearActuatorTypeConfig { + private final float size; + private final Supplier phase; + + public SineLinearActuatorConfig(float size, Supplier phase) { + this.size = size; + this.phase = phase; + } + + @Override + public LinearActuatorMode createActuatorMode() { + return new SineMode(size, phase.get().shortValue()); + } + + public static SineLinearActuatorConfig fromConfigurationSection(ConfigurationSection configurationSection) { + float size = (float)getDouble(configurationSection, "size", 1d); + Supplier phase = getIntSupplier(configurationSection, "phase", 0); + + return new SineLinearActuatorConfig(size, phase); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/playercontrol/PlayerControlConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/playercontrol/PlayerControlConfig.java new file mode 100644 index 00000000..5547e884 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/playercontrol/PlayerControlConfig.java @@ -0,0 +1,9 @@ +package com.jverbruggen.jrides.config.flatride.structure.actuator.playercontrol; + +import com.jverbruggen.jrides.animator.flatride.rotor.RotorPlayerControl; + +public interface PlayerControlConfig { + RotorPlayerControl createADPlayerControl(); + RotorPlayerControl createWSPlayerControl(); + RotorPlayerControl createSpaceBarPlayerControl(); +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/playercontrol/SpeedControlConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/playercontrol/SpeedControlConfig.java new file mode 100644 index 00000000..ea9486fe --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/playercontrol/SpeedControlConfig.java @@ -0,0 +1,37 @@ +package com.jverbruggen.jrides.config.flatride.structure.actuator.playercontrol; + +import com.jverbruggen.jrides.animator.flatride.rotor.RotorPlayerControl; +import com.jverbruggen.jrides.animator.flatride.rotor.RotorSpeedPlayerControl; +import com.jverbruggen.jrides.animator.flatride.rotor.controltype.ADControl; +import com.jverbruggen.jrides.animator.flatride.rotor.controltype.ControlType; +import com.jverbruggen.jrides.animator.flatride.rotor.controltype.SpaceBarControl; +import com.jverbruggen.jrides.animator.flatride.rotor.controltype.WSControl; + +public class SpeedControlConfig implements PlayerControlConfig { + private final double lowerSpeed; + private final double upperSpeed; + private final double accelerate; + + public SpeedControlConfig(double lowerSpeed, double upperSpeed, double accelerate) { + this.lowerSpeed = lowerSpeed; + this.upperSpeed = upperSpeed; + this.accelerate = accelerate; + } + + @Override + public RotorPlayerControl createADPlayerControl(){ + ControlType controlType = new ADControl(); + return new RotorSpeedPlayerControl(lowerSpeed, upperSpeed, accelerate, controlType); + } + + @Override + public RotorPlayerControl createWSPlayerControl() { + return new RotorSpeedPlayerControl(lowerSpeed, upperSpeed, accelerate, new WSControl()); + } + + @Override + public RotorPlayerControl createSpaceBarPlayerControl() { + ControlType controlType = new SpaceBarControl(); + return new RotorSpeedPlayerControl(lowerSpeed, upperSpeed, accelerate, controlType); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/playercontrol/TowardsPositionControlConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/playercontrol/TowardsPositionControlConfig.java new file mode 100644 index 00000000..828e39ba --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/playercontrol/TowardsPositionControlConfig.java @@ -0,0 +1,37 @@ +package com.jverbruggen.jrides.config.flatride.structure.actuator.playercontrol; + +import com.jverbruggen.jrides.animator.flatride.rotor.RotorPlayerControl; +import com.jverbruggen.jrides.animator.flatride.rotor.RotorTargetPositionPlayerControl; +import com.jverbruggen.jrides.animator.flatride.rotor.controltype.ADControl; +import com.jverbruggen.jrides.animator.flatride.rotor.controltype.ControlType; +import com.jverbruggen.jrides.animator.flatride.rotor.controltype.SpaceBarControl; +import com.jverbruggen.jrides.animator.flatride.rotor.controltype.WSControl; + +public class TowardsPositionControlConfig implements PlayerControlConfig { + private final double lowerPosition; + private final double upperPosition; + private final double accelerate; + + public TowardsPositionControlConfig(double lowerPosition, double upperPosition, double accelerate) { + this.lowerPosition = lowerPosition; + this.upperPosition = upperPosition; + this.accelerate = accelerate; + } + + @Override + public RotorPlayerControl createADPlayerControl(){ + ControlType controlType = new ADControl(); + return new RotorTargetPositionPlayerControl(lowerPosition, upperPosition, accelerate, controlType); + } + + @Override + public RotorPlayerControl createWSPlayerControl() { + return new RotorTargetPositionPlayerControl(lowerPosition, upperPosition, accelerate, new WSControl()); + } + + @Override + public RotorPlayerControl createSpaceBarPlayerControl() { + ControlType controlType = new SpaceBarControl(); + return new RotorTargetPositionPlayerControl(lowerPosition, upperPosition, accelerate, controlType); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/rotor/ContinuousRotorConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/rotor/ContinuousRotorConfig.java new file mode 100644 index 00000000..021b9fc9 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/rotor/ContinuousRotorConfig.java @@ -0,0 +1,27 @@ +package com.jverbruggen.jrides.config.flatride.structure.actuator.rotor; + +import com.jverbruggen.jrides.animator.flatride.rotor.mode.ContinuousMode; +import com.jverbruggen.jrides.animator.flatride.rotor.mode.RotorActuatorMode; +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +public class ContinuousRotorConfig extends BaseConfig implements RotorTypeConfig { + private final Double lowerBound; + private final Double upperBound; + + public ContinuousRotorConfig(Double lowerBound, Double upperBound) { + this.lowerBound = lowerBound; + this.upperBound = upperBound; + } + + @Override + public RotorActuatorMode createActuatorMode() { + return new ContinuousMode(lowerBound, upperBound); + } + + public static ContinuousRotorConfig fromConfigurationSection(ConfigurationSection configurationSection) { + Double lowerBound = getDoubleObj(configurationSection, "lowerBound", null); + Double upperBound = getDoubleObj(configurationSection, "upperBound", null); + return new ContinuousRotorConfig(lowerBound, upperBound); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/rotor/RotorTypeConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/rotor/RotorTypeConfig.java new file mode 100644 index 00000000..55f2a40f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/rotor/RotorTypeConfig.java @@ -0,0 +1,7 @@ +package com.jverbruggen.jrides.config.flatride.structure.actuator.rotor; + +import com.jverbruggen.jrides.animator.flatride.rotor.mode.RotorActuatorMode; + +public interface RotorTypeConfig { + RotorActuatorMode createActuatorMode(); +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/rotor/SineRotorConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/rotor/SineRotorConfig.java new file mode 100644 index 00000000..0213b22a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/actuator/rotor/SineRotorConfig.java @@ -0,0 +1,30 @@ +package com.jverbruggen.jrides.config.flatride.structure.actuator.rotor; + +import com.jverbruggen.jrides.animator.flatride.rotor.mode.RotorActuatorMode; +import com.jverbruggen.jrides.animator.flatride.rotor.mode.SineMode; +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.function.Supplier; + +public class SineRotorConfig extends BaseConfig implements RotorTypeConfig { + private final float size; + private final Supplier phase; + + public SineRotorConfig(float size, Supplier phase) { + this.size = size; + this.phase = phase; + } + + @Override + public RotorActuatorMode createActuatorMode() { + return new SineMode(size, phase.get().shortValue()); + } + + public static SineRotorConfig fromConfigurationSection(ConfigurationSection configurationSection) { + float size = (float)getDouble(configurationSection, "size", 1d); + Supplier phase = getIntSupplier(configurationSection, "phase", 0); + + return new SineRotorConfig(size, phase); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/attachment/AbstractRelativeMultipleAttachmentConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/attachment/AbstractRelativeMultipleAttachmentConfig.java new file mode 100644 index 00000000..baad9105 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/attachment/AbstractRelativeMultipleAttachmentConfig.java @@ -0,0 +1,29 @@ +package com.jverbruggen.jrides.config.flatride.structure.attachment; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.models.math.Vector3; + +public abstract class AbstractRelativeMultipleAttachmentConfig extends BaseConfig implements AttachmentConfig { + private final String toComponentIdentifier; + private final Vector3 offsetPosition; + private final int amount; + + protected AbstractRelativeMultipleAttachmentConfig(String toComponentIdentifier, Vector3 offsetPosition, int amount) { + this.toComponentIdentifier = toComponentIdentifier; + this.offsetPosition = offsetPosition; + this.amount = amount; + } + + public String getToComponentIdentifier() { + return toComponentIdentifier; + } + + public Vector3 getOffsetPosition() { + return offsetPosition; + } + + public int getAmount() { + return amount; + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/attachment/AttachmentConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/attachment/AttachmentConfig.java new file mode 100644 index 00000000..7aaffe4d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/attachment/AttachmentConfig.java @@ -0,0 +1,19 @@ +package com.jverbruggen.jrides.config.flatride.structure.attachment; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.config.flatride.structure.actuator.LimbConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.LinearActuatorConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.RotorConfig; +import com.jverbruggen.jrides.config.flatride.structure.basic.StaticStructureConfig; +import com.jverbruggen.jrides.config.flatride.structure.seat.SeatConfig; + +import java.util.List; + +public interface AttachmentConfig { + void createStaticStructureWithAttachment(StaticStructureConfig config, List components, FlatRideHandle rideHandle); + void createRotorWithAttachment(RotorConfig config, List components, FlatRideHandle rideHandle); + void createSeatWithAttachment(SeatConfig config, List components, FlatRideHandle rideHandle); + void createLinearActuator(LinearActuatorConfig linearActuatorConfig, List components, FlatRideHandle rideHandle); + void createLimb(LimbConfig linearActuatorConfig, List components, FlatRideHandle rideHandle, String preloadAnim); +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/attachment/FixedAttachmentConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/attachment/FixedAttachmentConfig.java new file mode 100644 index 00000000..49dc8563 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/attachment/FixedAttachmentConfig.java @@ -0,0 +1,123 @@ +package com.jverbruggen.jrides.config.flatride.structure.attachment; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.animator.flatride.Limb; +import com.jverbruggen.jrides.animator.flatride.attachment.Attachment; +import com.jverbruggen.jrides.animator.flatride.attachment.FixedAttachment; +import com.jverbruggen.jrides.animator.flatride.linearactuator.LinearActuator; +import com.jverbruggen.jrides.animator.flatride.rotor.FlatRideModel; +import com.jverbruggen.jrides.animator.flatride.rotor.Rotor; +import com.jverbruggen.jrides.animator.flatride.rotor.axis.RotorAxisFactory; +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.LimbConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.LinearActuatorConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.RotorConfig; +import com.jverbruggen.jrides.config.flatride.structure.basic.StaticStructureConfig; +import com.jverbruggen.jrides.config.flatride.structure.seat.SeatConfig; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.math.VectorQuaternionState; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.flatride.Animation; +import com.jverbruggen.jrides.state.ride.flatride.AnimationHandle; +import com.jverbruggen.jrides.state.ride.flatride.AnimationLoader; +import com.jverbruggen.jrides.state.viewport.ViewportManager; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.List; +import java.util.stream.Collectors; + +public class FixedAttachmentConfig extends BaseConfig implements AttachmentConfig { + private final Vector3 position; + private final Quaternion rotation; + + public FixedAttachmentConfig(Vector3 position, Quaternion rotation) { + this.position = position; + this.rotation = rotation; + } + + public static AttachmentConfig fromConfigurationSection(ConfigurationSection configurationSection) { + Vector3 position = Vector3.fromDoubleList(getDoubleList(configurationSection, "position")); + Quaternion rotation = Quaternion.fromDoubleList(getDoubleList(configurationSection, "rotation", List.of(0d,0d,0d))); + + return new FixedAttachmentConfig(position, rotation); + } + + @Override + public void createSeatWithAttachment(SeatConfig config, List components, FlatRideHandle rideHandle) { + throw new RuntimeException("Attaching seat to fixed point not implemented. Also kinda weird."); + } + + @Override + public void createLinearActuator(LinearActuatorConfig linearActuatorConfig, List components, FlatRideHandle rideHandle) { + ViewportManager viewportManager = ServiceProvider.getSingleton(ViewportManager.class); + + List flatRideModels = linearActuatorConfig.getFlatRideModels().stream() + .map(config -> config.toFlatRideModel(position, viewportManager)) + .collect(Collectors.toList()); + + LinearActuator linearActuator = new LinearActuator( + linearActuatorConfig.getIdentifier(), linearActuatorConfig.getIdentifier(), + linearActuatorConfig.isRoot(), null, + flatRideModels, + linearActuatorConfig.getFlatRideComponentSpeed(), + linearActuatorConfig.getLinearActuatorTypeConfig().createActuatorMode()); + + Attachment attachment = new FixedAttachment(linearActuator, position, rotation); + linearActuator.setAttachedTo(attachment); + + components.add(linearActuator); + } + + @Override + public void createLimb(LimbConfig limbConfig, List components, FlatRideHandle rideHandle, String preloadAnim) { + ViewportManager viewportManager = ServiceProvider.getSingleton(ViewportManager.class); + + List flatRideModels = limbConfig.getFlatRideModels().stream() + .map(config -> config.toFlatRideModel(position, viewportManager)) + .collect(Collectors.toList()); + + String limbIdentifier = limbConfig.getIdentifier(); + VectorQuaternionState vectorQuaternionState = Limb.getInitialPoseFromAnimation(preloadAnim, limbIdentifier, rideHandle); + + Limb limb = new Limb( + limbIdentifier, + limbIdentifier, + limbConfig.isRoot(), + null, + flatRideModels, + vectorQuaternionState + ); + + Attachment attachment = new FixedAttachment(limb, position, rotation); + limb.setAttachedTo(attachment); + + components.add(limb); + } + + @Override + public void createStaticStructureWithAttachment(StaticStructureConfig config, List components, FlatRideHandle rideHandle) { + throw new RuntimeException("Not implementing this functionality. Weird."); + } + + @Override + public void createRotorWithAttachment(RotorConfig rotorConfig, List components, FlatRideHandle rideHandle) { + ViewportManager viewportManager = ServiceProvider.getSingleton(ViewportManager.class); + + List flatRideModels = rotorConfig.getFlatRideModels().stream() + .map(config -> config.toFlatRideModel(position, viewportManager)) + .collect(Collectors.toList()); + + Rotor rotor = new Rotor(rotorConfig.getIdentifier(), rotorConfig.getIdentifier(), rotorConfig.isRoot(), + null, flatRideModels, rotorConfig.getFlatRideComponentSpeed(), + RotorAxisFactory.createAxisFromString(rotorConfig.getRotorAxis()), + rotorConfig.getRotorTypeConfig().createActuatorMode()); + rotor.createPlayerControl(rotorConfig.getPlayerControlConfig()); + + Attachment attachment = new FixedAttachment(rotor, position, rotation); + rotor.setAttachedTo(attachment); + + components.add(rotor); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/attachment/RelativeMultipleAttachmentConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/attachment/RelativeMultipleAttachmentConfig.java new file mode 100644 index 00000000..5b96e903 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/attachment/RelativeMultipleAttachmentConfig.java @@ -0,0 +1,140 @@ +package com.jverbruggen.jrides.config.flatride.structure.attachment; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.animator.flatride.Limb; +import com.jverbruggen.jrides.config.flatride.structure.actuator.LimbConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.LinearActuatorConfig; +import com.jverbruggen.jrides.config.flatride.structure.actuator.RotorConfig; +import com.jverbruggen.jrides.config.flatride.structure.attachment.joint.RelativeAttachmentJointConfig; +import com.jverbruggen.jrides.config.flatride.structure.basic.StaticStructureConfig; +import com.jverbruggen.jrides.config.flatride.structure.seat.SeatConfig; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.math.VectorQuaternionState; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.List; + +public class RelativeMultipleAttachmentConfig extends AbstractRelativeMultipleAttachmentConfig { + private final RelativeAttachmentJointConfig joint; + + protected RelativeMultipleAttachmentConfig(String toComponentIdentifier, Vector3 offsetPosition, int amount, RelativeAttachmentJointConfig joint) { + super(toComponentIdentifier, offsetPosition, amount); + this.joint = joint; + } + + public RelativeAttachmentJointConfig getJoint() { + return joint; + } + + public static AttachmentConfig fromConfigurationSection(ConfigurationSection configurationSection) { + String armTo = getString(configurationSection, "arm"); + Vector3 offsetPosition; + if(configurationSection.contains("armDistance")) + offsetPosition = new Vector3(getDouble(configurationSection, "armDistance"), 0, 0); + else if(configurationSection.contains("armOffset")) + offsetPosition = Vector3.fromDoubleList(getDoubleList(configurationSection, "armOffset")); + else offsetPosition = Vector3.zero(); + + int armDuplicate = getInt(configurationSection, "armDuplicate", 1); + + RelativeAttachmentJointConfig joint = RelativeAttachmentJointConfig.fromConfigurationSection(configurationSection.getConfigurationSection("armJoint")); + + return new RelativeMultipleAttachmentConfig(armTo, offsetPosition, armDuplicate, joint); + } + + @Override + public void createSeatWithAttachment(SeatConfig seatConfig, List components, FlatRideHandle rideHandle) { + List attachedToComponents = FlatRideComponent.findAllMatching(components, getToComponentIdentifier()); + + for(FlatRideComponent attachedTo : attachedToComponents){ + List createdComponents = FlatRideComponent.createDistributedSeats( + rideHandle, + seatConfig.getIdentifier(), + attachedTo, + new Quaternion(), + getOffsetPosition(), + seatConfig.getSeatYawOffset(), + seatConfig.getFlatRideModels(), + getAmount()); + + components.addAll(createdComponents); + } + } + + @Override + public void createLinearActuator(LinearActuatorConfig linearActuatorConfig, List components, FlatRideHandle rideHandle) { + List attachedToComponents = FlatRideComponent.findAllMatching(components, getToComponentIdentifier()); + + for(FlatRideComponent attachedTo : attachedToComponents){ + List createdComponents = FlatRideComponent.createDistributedLinearActuators( + attachedTo, + new Quaternion(), + getOffsetPosition(), + linearActuatorConfig, + getAmount()); + + components.addAll(createdComponents); + } + } + + @Override + public void createLimb(LimbConfig limbConfig, List components, FlatRideHandle rideHandle, String preloadAnim) { + List attachedToComponents = FlatRideComponent.findAllMatching(components, getToComponentIdentifier()); + + String limbIdentifier = limbConfig.getIdentifier(); + VectorQuaternionState initialPose = Limb.getInitialPoseFromAnimation(preloadAnim, limbIdentifier, rideHandle); + + for(FlatRideComponent attachedTo : attachedToComponents){ + List createdComponents = FlatRideComponent.createLimb( + attachedTo, + new Quaternion(), + getOffsetPosition(), + limbConfig, + initialPose); + + components.addAll(createdComponents); + } + } + + @Override + public void createStaticStructureWithAttachment(StaticStructureConfig config, List components, FlatRideHandle rideHandle) { + List attachedToComponents = FlatRideComponent.findAllMatching(components, getToComponentIdentifier()); + for(FlatRideComponent attachedTo : attachedToComponents) { + FlatRideComponent component = FlatRideComponent.createStaticStructure( + config.getIdentifier(), + config.getIdentifier(), + attachedTo, + new Quaternion(), + getOffsetPosition(), + getJoint(), + config.getFlatRideModels() + ); + + components.add(component); + } + } + + @Override + public void createRotorWithAttachment(RotorConfig rotorConfig, List components, FlatRideHandle rideHandle) { + List attachedToComponents = FlatRideComponent.findAllMatching(components, getToComponentIdentifier()); + + for(FlatRideComponent attachedTo : attachedToComponents){ + List createdComponents = FlatRideComponent.createDistributedAttachedRotors( + rotorConfig.getIdentifier(), + attachedTo, + new Quaternion(), + getOffsetPosition(), + rotorConfig.getFlatRideComponentSpeed(), + rotorConfig.getRotorTypeConfig().createActuatorMode(), + rotorConfig.getPlayerControlConfig(), + getJoint(), + rotorConfig.getRotorAxis(), + rotorConfig.getFlatRideModels(), + getAmount()); + + components.addAll(createdComponents); + } + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/attachment/joint/RelativeAttachmentJointConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/attachment/joint/RelativeAttachmentJointConfig.java new file mode 100644 index 00000000..050670ef --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/attachment/joint/RelativeAttachmentJointConfig.java @@ -0,0 +1,74 @@ +package com.jverbruggen.jrides.config.flatride.structure.attachment.joint; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +public final class RelativeAttachmentJointConfig extends BaseConfig { + private final boolean isFixedX; + private final boolean isFixedY; + private final boolean isFixedZ; + private final double fixX; + private final double fixY; + private final double fixZ; + + public RelativeAttachmentJointConfig(boolean isFixedX, boolean isFixedY, boolean isFixedZ, double fixX, double fixY, double fixZ) { + this.isFixedX = isFixedX; + this.isFixedY = isFixedY; + this.isFixedZ = isFixedZ; + this.fixX = fixX; + this.fixY = fixY; + this.fixZ = fixZ; + } + + + public boolean isFixedX() { + return isFixedX; + } + + public boolean isFixedY() { + return isFixedY; + } + + public boolean isFixedZ() { + return isFixedZ; + } + + public double getFixX() { + return fixX; + } + + public double getFixY() { + return fixY; + } + + public double getFixZ() { + return fixZ; + } + + public boolean anyFixed(){ + return isFixedX || isFixedY || isFixedZ; + } + + public static RelativeAttachmentJointConfig fromConfigurationSection(ConfigurationSection configurationSection) { + if(configurationSection == null) return new RelativeAttachmentJointConfig(false, false, false, 0, 0, 0); + + Double fixX = null; + Double fixY = null; + Double fixZ = null; + + if(configurationSection.contains("fixX")) + fixX = getDouble(configurationSection, "fixX"); + if(configurationSection.contains("fixY")) + fixY = getDouble(configurationSection, "fixY"); + if(configurationSection.contains("fixZ")) + fixZ = getDouble(configurationSection, "fixZ"); + + return new RelativeAttachmentJointConfig(fixX != null, fixY != null, fixZ != null, + getDoubleOrElseNull(fixX), getDoubleOrElseNull(fixY), getDoubleOrElseNull(fixZ)); + } + + private static double getDoubleOrElseNull(Double d){ + if(d == null) return 0d; + return d; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/basic/StaticStructureConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/basic/StaticStructureConfig.java new file mode 100644 index 00000000..2f16feb2 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/basic/StaticStructureConfig.java @@ -0,0 +1,47 @@ +package com.jverbruggen.jrides.config.flatride.structure.basic; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.config.coaster.objects.cart.ModelConfig; +import com.jverbruggen.jrides.config.flatride.structure.AbstractStructureConfig; +import com.jverbruggen.jrides.config.flatride.structure.StructureConfigItem; +import com.jverbruggen.jrides.config.flatride.structure.attachment.AttachmentConfig; +import com.jverbruggen.jrides.config.flatride.structure.attachment.FixedAttachmentConfig; +import com.jverbruggen.jrides.config.flatride.structure.attachment.RelativeMultipleAttachmentConfig; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.ArrayList; +import java.util.List; + +public class StaticStructureConfig extends AbstractStructureConfig { + public StaticStructureConfig(String identifier, boolean root, List flatRideModels, AttachmentConfig attachmentConfig) { + super(identifier, root, flatRideModels, attachmentConfig); + } + + @Override + public void createAndAddTo(List components, FlatRideHandle rideHandle) { + getAttachmentConfig().createStaticStructureWithAttachment(this, components, rideHandle); + } + + public static StructureConfigItem fromConfigurationSection(ConfigurationSection configurationSection, String identifier) { + boolean root = getBoolean(configurationSection, "root", false); + + AttachmentConfig attachmentConfig = null; + if(configurationSection.contains("position")){ + attachmentConfig = FixedAttachmentConfig.fromConfigurationSection(configurationSection); + } + if(configurationSection.contains("arm")){ + if(attachmentConfig != null) throw new RuntimeException("Can only create one attachment type for a rotor"); + attachmentConfig = RelativeMultipleAttachmentConfig.fromConfigurationSection(configurationSection); + } + + if(attachmentConfig == null) throw new RuntimeException("No attachment specified for rotor"); + + List modelConfigs; + if(configurationSection.contains("models")) + modelConfigs = ModelConfig.multipleFromConfigurationSection(getConfigurationSection(configurationSection, "models")); + else modelConfigs = new ArrayList<>(); + + return new StaticStructureConfig(identifier, root, modelConfigs, attachmentConfig); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/structure/seat/SeatConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/seat/SeatConfig.java new file mode 100644 index 00000000..346bd275 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/structure/seat/SeatConfig.java @@ -0,0 +1,69 @@ +package com.jverbruggen.jrides.config.flatride.structure.seat; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.config.coaster.objects.cart.ModelConfig; +import com.jverbruggen.jrides.config.flatride.structure.StructureConfigItem; +import com.jverbruggen.jrides.config.flatride.structure.attachment.AttachmentConfig; +import com.jverbruggen.jrides.config.flatride.structure.attachment.RelativeMultipleAttachmentConfig; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.ArrayList; +import java.util.List; + +public class SeatConfig extends BaseConfig implements StructureConfigItem { + private final String identifier; + private final AttachmentConfig attachmentConfig; + private final List flatRideModels; + private final int seatYawOffset; + + public SeatConfig(String identifier, AttachmentConfig attachmentConfig, List flatRideModels, int seatYawOffset) { + this.identifier = identifier; + this.attachmentConfig = attachmentConfig; + this.flatRideModels = flatRideModels; + this.seatYawOffset = seatYawOffset; + } + + @Override + public String getIdentifier() { + return identifier; + } + + @Override + public void createAndAddTo(List components, FlatRideHandle rideHandle) { + attachmentConfig.createSeatWithAttachment(this, components, rideHandle); + } + + public AttachmentConfig getAttachmentConfig() { + return attachmentConfig; + } + + public List getFlatRideModels() { + return flatRideModels; + } + + + public int getSeatYawOffset() { + return seatYawOffset; + } + + public static StructureConfigItem fromConfigurationSection(ConfigurationSection configurationSection, String identifier) { + AttachmentConfig attachmentConfig = null; + if(configurationSection.contains("arm")){ + attachmentConfig = RelativeMultipleAttachmentConfig.fromConfigurationSection(configurationSection); + } + + if(attachmentConfig == null) throw new RuntimeException("No attachment specified for rotor"); + + List modelConfigs; + if(configurationSection.contains("models")) + modelConfigs = ModelConfig.multipleFromConfigurationSection(getConfigurationSection(configurationSection, "models")); + else modelConfigs = new ArrayList<>(); + + int seatYawOffset = getInt(configurationSection, "seatRotationDegrees", 0); + + return new SeatConfig(identifier, attachmentConfig, modelConfigs, seatYawOffset); + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/timing/ActionConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/timing/ActionConfig.java new file mode 100644 index 00000000..f38e0251 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/timing/ActionConfig.java @@ -0,0 +1,11 @@ +package com.jverbruggen.jrides.config.flatride.timing; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.animator.flatride.timing.instruction.TimingAction; + +import java.util.List; + +public interface ActionConfig { + List getTimingAction(FlatRideHandle flatRideHandle, List flatRideComponents); +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/timing/ActionConfigFactory.java b/src/main/java/com/jverbruggen/jrides/config/flatride/timing/ActionConfigFactory.java new file mode 100644 index 00000000..0acd8392 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/timing/ActionConfigFactory.java @@ -0,0 +1,45 @@ +package com.jverbruggen.jrides.config.flatride.timing; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; + +public class ActionConfigFactory extends BaseConfig { + public static List fromConfigurationSection(@Nullable ConfigurationSection configurationSection){ + List actionConfigs = new ArrayList<>(); + if(configurationSection == null) return actionConfigs; + + for(String key : configurationSection.getKeys(false)){ + ConfigurationSection actionConfigurationSection = configurationSection.getConfigurationSection(key); + assert actionConfigurationSection != null; + + if(actionConfigurationSection.contains("animation")){ + actionConfigs.add(createAnimationActionConfig(key, actionConfigurationSection)); + continue; + } + + SimpleActionConfig actionConfig = new SimpleActionConfig(key); + if(actionConfigurationSection.contains("speed")) + actionConfig.setSpeed((float) getDouble(actionConfigurationSection, "speed")); + if(actionConfigurationSection.contains("accelerate")) + actionConfig.setAccelerate((float) getDouble(actionConfigurationSection, "accelerate")); + if(actionConfigurationSection.contains("allowControl")) + actionConfig.setAllowControl(getBoolean(actionConfigurationSection, "allowControl")); + if(actionConfigurationSection.contains("targetPosition")) + actionConfig.setTargetPosition((float) getDouble(actionConfigurationSection, "targetPosition")); + + actionConfigs.add(actionConfig); + } + + return actionConfigs; + } + + public static ActionConfig createAnimationActionConfig(String targetIdentifier, @Nullable ConfigurationSection configurationSection){ + String animation = getString(configurationSection, "animation"); + + return new AnimationActionConfig(animation, targetIdentifier); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/timing/AnimationActionConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/timing/AnimationActionConfig.java new file mode 100644 index 00000000..dbb0bf5a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/timing/AnimationActionConfig.java @@ -0,0 +1,43 @@ +package com.jverbruggen.jrides.config.flatride.timing; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.animator.flatride.timing.instruction.AnimationInstruction; +import com.jverbruggen.jrides.animator.flatride.timing.instruction.InstructionBinding; +import com.jverbruggen.jrides.animator.flatride.timing.instruction.TimingAction; +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.flatride.AnimationHandle; +import com.jverbruggen.jrides.state.ride.flatride.AnimationLoader; + +import java.util.ArrayList; +import java.util.List; + +public class AnimationActionConfig extends BaseConfig implements ActionConfig{ + private final String animation; + private final String targetIdentifier; + + public AnimationActionConfig(String animation, String targetIdentifier) { + this.animation = animation; + this.targetIdentifier = targetIdentifier; + } + + public String getAnimation() { + return animation; + } + + @Override + public List getTimingAction(FlatRideHandle flatRideHandle, List flatRideComponents) { + List targetedFlatRideComponents = flatRideComponents.stream() + .filter(c -> c.equalsToIdentifier(targetIdentifier)) + .toList(); + + List timingActions = new ArrayList<>(); + AnimationLoader animationLoader = ServiceProvider.getSingleton(AnimationLoader.class); + + AnimationHandle animationHandle = animationLoader.loadFlatRideAnimation(this.animation, flatRideHandle); + timingActions.add(new InstructionBinding(new AnimationInstruction(animationHandle), targetedFlatRideComponents)); + + return timingActions; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/timing/SimpleActionConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/timing/SimpleActionConfig.java new file mode 100644 index 00000000..7093952c --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/timing/SimpleActionConfig.java @@ -0,0 +1,91 @@ +package com.jverbruggen.jrides.config.flatride.timing; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.animator.flatride.interfaces.HasPosition; +import com.jverbruggen.jrides.animator.flatride.timing.instruction.*; +import com.jverbruggen.jrides.animator.flatride.timing.instruction.towards.TowardsPositionInstruction; +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class SimpleActionConfig extends BaseConfig implements ActionConfig { + private final String targetIdentifier; + private Float speed; + private Float accelerate; + private Boolean allowControl; + private Float targetPosition; + + public SimpleActionConfig(String targetIdentifier) { + this.targetIdentifier = targetIdentifier; + speed = null; + accelerate = null; + allowControl = null; + targetPosition = null; + } + + public Float getSpeed() { + return speed; + } + + public void setSpeed(Float speed) { + this.speed = speed; + } + + public Float getAccelerate() { + return accelerate == null ? 0 : Math.abs(accelerate); + } + + public void setAccelerate(Float accelerate) { + this.accelerate = accelerate; + } + + public Boolean allowsControl() { + return allowControl; + } + + public void setAllowControl(Boolean allowControl) { + this.allowControl = allowControl; + } + + public Float getTargetPosition() { + return targetPosition; + } + + public void setTargetPosition(Float targetPosition) { + this.targetPosition = targetPosition; + } + + @Override + public List getTimingAction(FlatRideHandle flatRideHandle, List flatRideComponents){ + List targetedFlatRideComponents = flatRideComponents.stream() + .filter(c -> c.equalsToIdentifier(targetIdentifier)) + .toList(); + + if(targetedFlatRideComponents.size() == 0) return Collections.emptyList(); + + List timingActions = new ArrayList<>(); + if(targetPosition != null){ + HasPosition sampleComponent = (HasPosition) targetedFlatRideComponents.get(0); + double minSpeed = getSpeed() != null ? getSpeed() : sampleComponent.getFlatRideComponentSpeed().getMinSpeed(); + double maxSpeed = getSpeed() != null ? -getSpeed() : sampleComponent.getFlatRideComponentSpeed().getMaxSpeed(); + + timingActions.add(new InstructionBinding( + new TowardsPositionInstruction(getAccelerate(), minSpeed, maxSpeed, getTargetPosition()), targetedFlatRideComponents)); + }else if(speed != null){ // SpeedInstruction and TowardsPositionInstruction are mutually exclusive. + timingActions.add(new InstructionBinding( + new SpeedInstruction(getAccelerate(), getSpeed()), targetedFlatRideComponents)); + } + if(allowControl != null){ + if(targetPosition != null && allowControl) throw new RuntimeException("No support for target position and control"); + timingActions.add(new InstructionBinding( + new ControlInstruction(allowsControl()), targetedFlatRideComponents)); + } + + return timingActions; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/timing/TimingConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/timing/TimingConfig.java new file mode 100644 index 00000000..4c7d7ec0 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/timing/TimingConfig.java @@ -0,0 +1,53 @@ +package com.jverbruggen.jrides.config.flatride.timing; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.animator.flatride.timing.TimingSequence; +import com.jverbruggen.jrides.animator.flatride.timing.instruction.InstructionSequenceItem; +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +public class TimingConfig extends BaseConfig { + private final List phases; + + public TimingConfig(List phases) { + this.phases = phases; + } + + public List getPhases() { + return phases; + } + + public static TimingConfig fromConfigurationSection(@Nullable ConfigurationSection configurationSection) { + List items = new ArrayList<>(); + + if(configurationSection != null){ + Set phases = configurationSection.getKeys(false); + for(String phase : phases){ + ConfigurationSection itemConfigurationSection = getConfigurationSection(configurationSection, phase); + if(itemConfigurationSection == null) throw new RuntimeException("No contents in phase " + phase); + + TimingPhaseConfig structureConfigItem = TimingPhaseConfig.fromConfigurationSection( + getConfigurationSection(configurationSection, phase), phase); + + if(structureConfigItem != null) + items.add(structureConfigItem); + } + } + + return new TimingConfig(items); + } + + public TimingSequence createTimingSequence(FlatRideHandle flatRideHandle, List flatRideComponents) { + List items = new ArrayList<>(); + for(TimingPhaseConfig phaseConfig : getPhases()){ + items.add(phaseConfig.getInstructionSequenceItem(flatRideHandle, flatRideComponents)); + } + return new TimingSequence(items); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/flatride/timing/TimingPhaseConfig.java b/src/main/java/com/jverbruggen/jrides/config/flatride/timing/TimingPhaseConfig.java new file mode 100644 index 00000000..a028c4a7 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/flatride/timing/TimingPhaseConfig.java @@ -0,0 +1,46 @@ +package com.jverbruggen.jrides.config.flatride.timing; + +import com.jverbruggen.jrides.animator.flatride.FlatRideComponent; +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.animator.flatride.timing.instruction.InstructionSequenceItem; +import com.jverbruggen.jrides.animator.flatride.timing.instruction.TimingAction; +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +import javax.annotation.Nullable; +import java.util.List; + +public class TimingPhaseConfig extends BaseConfig { + @SuppressWarnings("unused") + private final String phaseIdentifier; //TODO: integrate + private final int durationTicks; + private final List actions; + public TimingPhaseConfig(String phaseIdentifier, int durationTicks, List actions) { + this.phaseIdentifier = phaseIdentifier; + this.durationTicks = durationTicks; + this.actions = actions; + } + + public int getDurationTicks() { + return durationTicks; + } + + public static TimingPhaseConfig fromConfigurationSection(@Nullable ConfigurationSection configurationSection, String phaseIdentifier) { + if(configurationSection == null) return null; + + int durationTicks = getInt(configurationSection, "durationTicks"); + List actions = ActionConfigFactory.fromConfigurationSection( + getConfigurationSection(configurationSection, "actions")); + + return new TimingPhaseConfig(phaseIdentifier, durationTicks, actions); + } + + public InstructionSequenceItem getInstructionSequenceItem(FlatRideHandle flatRideHandle, List flatRideComponents){ + int durationTicks = this.getDurationTicks(); + List timingActions = actions.stream() + .flatMap(a -> a.getTimingAction(flatRideHandle, flatRideComponents).stream()) + .toList(); + + return new InstructionSequenceItem(durationTicks, timingActions); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/gates/GateConfig.java b/src/main/java/com/jverbruggen/jrides/config/gates/GateConfig.java new file mode 100644 index 00000000..69b47709 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/gates/GateConfig.java @@ -0,0 +1,22 @@ +package com.jverbruggen.jrides.config.gates; + +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.ride.gate.GateType; + +public class GateConfig { + private final Vector3 location; + private final GateType type; + + public GateConfig(Vector3 location, GateType type) { + this.location = location; + this.type = type; + } + + public GateType getType() { + return type; + } + + public Vector3 getLocation() { + return location; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/gates/GateOwnerConfigSpec.java b/src/main/java/com/jverbruggen/jrides/config/gates/GateOwnerConfigSpec.java new file mode 100644 index 00000000..35a24072 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/gates/GateOwnerConfigSpec.java @@ -0,0 +1,68 @@ +package com.jverbruggen.jrides.config.gates; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.control.DispatchLockCollection; +import com.jverbruggen.jrides.control.SimpleDispatchLock; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.language.LanguageFileTag; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.ride.gate.FenceGate; +import com.jverbruggen.jrides.models.ride.gate.Gate; +import org.bukkit.World; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.ArrayList; +import java.util.List; + +public class GateOwnerConfigSpec { + private final GateSpecConfig gateSpecConfigEntry; + private final GateSpecConfig gateSpecConfigExit; + + public GateOwnerConfigSpec(GateSpecConfig gateSpecConfigEntry, GateSpecConfig gateSpecConfigExit) { + this.gateSpecConfigEntry = gateSpecConfigEntry; + this.gateSpecConfigExit = gateSpecConfigExit; + } + + public GateSpecConfig getGateSpecConfigEntry() { + return gateSpecConfigEntry; + } + + public GateSpecConfig getGateSpecConfigExit() { + return gateSpecConfigExit; + } + + public static GateOwnerConfigSpec fromConfigurationSection(ConfigurationSection configurationSection) { + if(configurationSection == null) + throw new RuntimeException("Configuration section not defined for gate"); + + GateSpecConfig gateSpecConfigEntry = null; + GateSpecConfig gateSpecConfigExit = null; + + if (configurationSection.contains("entry")) gateSpecConfigEntry = GateSpecConfig.fromConfigurationSection(configurationSection.getConfigurationSection("entry")); + if (configurationSection.contains("exit")) gateSpecConfigExit = GateSpecConfig.fromConfigurationSection(configurationSection.getConfigurationSection("exit")); + + return new GateOwnerConfigSpec(gateSpecConfigEntry, gateSpecConfigExit); + } + + public List createGates(String stationName, World world, DispatchLockCollection gatesGenericLock){ + LanguageFile languageFile = JRidesPlugin.getLanguageFile(); + List gates = new ArrayList<>(); + + List gateConfigs = getGateSpecConfigEntry().getGates(); + for(int i = 0; i < gateConfigs.size(); i++){ + GateConfig gateConfig = gateConfigs.get(i); + String gateName = stationName + "_gate_" + i; + Vector3 location = gateConfig.getLocation(); + final String gateDisplayName = "" + i; + gates.add(new FenceGate(gateName, + new SimpleDispatchLock(gatesGenericLock, + languageFile.get(LanguageFileField.NOTIFICATION_RIDE_GATE_NOT_CLOSED, + b -> b.add(LanguageFileTag.name, gateDisplayName)), + false), + location.toBukkitLocation(world).getBlock())); + } + + return gates; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/gates/GateSpecConfig.java b/src/main/java/com/jverbruggen/jrides/config/gates/GateSpecConfig.java new file mode 100644 index 00000000..b7b13dad --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/gates/GateSpecConfig.java @@ -0,0 +1,43 @@ +package com.jverbruggen.jrides.config.gates; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.ride.gate.GateType; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.ArrayList; +import java.util.List; + +public class GateSpecConfig extends BaseConfig { + private final List gates; + + public GateSpecConfig(List gates) { + this.gates = gates; + } + + public List getGates() { + return gates; + } + + public static GateSpecConfig fromConfigurationSection(ConfigurationSection configurationSection) { + List> positions = (List>) configurationSection.getList("positions"); + List gates = new ArrayList<>(); + + if(positions != null){ + for(List position : positions){ + if(position.size() == 3){ + Vector3 location = new Vector3(toDouble(position.get(0)), toDouble(position.get(1)), toDouble(position.get(2))); + gates.add(new GateConfig(location, GateType.DOOR_OR_GATE)); + }else if(position.size() == 4){ + Vector3 location = new Vector3(toDouble(position.get(0)), toDouble(position.get(1)), toDouble(position.get(2))); + GateType gateType = GateType.fromValue((String) position.get(3)); + gates.add(new GateConfig(location, gateType)); + }else{ + throw new RuntimeException("Gate position should be of format [x,y,z] or [x,y,z,'type']"); + } + } + } + + return new GateSpecConfig(gates); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/gates/GatesConfig.java b/src/main/java/com/jverbruggen/jrides/config/gates/GatesConfig.java new file mode 100644 index 00000000..e058c9b7 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/gates/GatesConfig.java @@ -0,0 +1,43 @@ +package com.jverbruggen.jrides.config.gates; + +import com.jverbruggen.jrides.JRidesPlugin; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.HashMap; +import java.util.Optional; +import java.util.Set; + +public class GatesConfig { + private final HashMap gateOwnerSpecs; + + public GatesConfig(HashMap gateOwnerSpecs) { + this.gateOwnerSpecs = gateOwnerSpecs; + } + + public GatesConfig() { + gateOwnerSpecs = null; + } + + public Optional getGateOwnerSpec(String ownerName){ + if(gateOwnerSpecs == null || !gateOwnerSpecs.containsKey(ownerName)){ + JRidesPlugin.getLogger().warning(ownerName + " has no gates!"); + return Optional.empty(); + } + + return Optional.of(gateOwnerSpecs.get(ownerName)); + } + + public static GatesConfig fromConfigurationSection(ConfigurationSection configurationSection) { + if(configurationSection == null) return new GatesConfig(); + + HashMap gateOwnerSpecs = new HashMap<>(); + Set gateOwners = configurationSection.getKeys(false); + + for(String gateOwner : gateOwners){ + GateOwnerConfigSpec spec = GateOwnerConfigSpec.fromConfigurationSection(configurationSection.getConfigurationSection(gateOwner)); + gateOwnerSpecs.put(gateOwner, spec); + } + + return new GatesConfig(gateOwnerSpecs); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/gates/StationConfig.java b/src/main/java/com/jverbruggen/jrides/config/gates/StationConfig.java new file mode 100644 index 00000000..2ce94bea --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/gates/StationConfig.java @@ -0,0 +1,77 @@ +package com.jverbruggen.jrides.config.gates; + +import com.jverbruggen.jrides.animator.flatride.station.FlatRideStationHandle; +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.config.coaster.objects.section.ranged.StationEffectsConfig; +import com.jverbruggen.jrides.control.DispatchLock; +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.effect.EffectTriggerFactory; +import com.jverbruggen.jrides.effect.handle.train.TrainEffectTriggerHandle; +import com.jverbruggen.jrides.models.properties.MinMaxWaitingTimer; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.ride.RideType; +import com.jverbruggen.jrides.models.ride.gate.Gate; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.List; + +public class StationConfig extends BaseConfig { + private final int minimumWaitIntervalSeconds; + private final int maximumWaitIntervalSeconds; + private final StationEffectsConfig stationEffectsConfig; + private final PlayerLocation ejectLocation; + + public StationConfig(int minimumWaitIntervalSeconds, int maximumWaitIntervalSeconds, StationEffectsConfig stationEffectsConfig, PlayerLocation ejectLocation) { + this.minimumWaitIntervalSeconds = minimumWaitIntervalSeconds; + this.maximumWaitIntervalSeconds = maximumWaitIntervalSeconds; + this.stationEffectsConfig = stationEffectsConfig; + this.ejectLocation = ejectLocation; + } + + public int getMinimumWaitIntervalSeconds() { + return minimumWaitIntervalSeconds; + } + + public int getMaximumWaitIntervalSeconds() { + return maximumWaitIntervalSeconds; + } + + public PlayerLocation getEjectLocation() { + return ejectLocation; + } + + public StationEffectsConfig getStationEffectsConfig() { + return stationEffectsConfig; + } + + public static StationConfig fromConfigurationSection(ConfigurationSection configurationSection) { + int minimumWaitIntervalSeconds = getInt(configurationSection, "minimumWaitIntervalSeconds", 15); + int maximumWaitIntervalSeconds = getInt(configurationSection, "maximumWaitIntervalSeconds", 45); + StationEffectsConfig effects = StationEffectsConfig.fromConfigurationSection(getConfigurationSection(configurationSection, "effects")); + PlayerLocation ejectLocation = PlayerLocation.fromDoubleList(getDoubleList(configurationSection, "ejectLocation")); + + return new StationConfig(minimumWaitIntervalSeconds, maximumWaitIntervalSeconds, effects, ejectLocation); + } + + public MinMaxWaitingTimer createWaitingTimer(DispatchLock dispatchLock){ + int minimumWaitingTime = getMinimumWaitIntervalSeconds(); + int maximumWaitingTime = getMaximumWaitIntervalSeconds(); + + return new MinMaxWaitingTimer(minimumWaitingTime, maximumWaitingTime, dispatchLock); + } + + public FlatRideStationHandle createFlatRideStationHandle(String rideIdentifier, String stationName, String shortStationName, TriggerContext triggerContext, List gates, DispatchLock minimumWaitTimeDispatchLock){ + EffectTriggerFactory effectTriggerFactory = ServiceProvider.getSingleton(EffectTriggerFactory.class); + + MinMaxWaitingTimer waitingTimer = createWaitingTimer(minimumWaitTimeDispatchLock); + List entryBlockingEffectTriggers = effectTriggerFactory.getFramelessEffectTriggers(RideType.FLATRIDE, rideIdentifier, stationEffectsConfig.getEntryBlockingEffects()); + List exitBlockingEffectTriggers = effectTriggerFactory.getFramelessEffectTriggers(RideType.FLATRIDE, rideIdentifier, stationEffectsConfig.getExitBlockingEffects()); + List exitEffectTriggers = effectTriggerFactory.getFramelessEffectTriggers(RideType.FLATRIDE, rideIdentifier, stationEffectsConfig.getExitEffects()); + + FlatRideStationHandle stationHandle = new FlatRideStationHandle(stationName, shortStationName, gates, getEjectLocation(), waitingTimer, triggerContext, entryBlockingEffectTriggers, exitBlockingEffectTriggers, exitEffectTriggers); + triggerContext.setParentStation(stationHandle); + + return stationHandle; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/ride/AbstractRideConfig.java b/src/main/java/com/jverbruggen/jrides/config/ride/AbstractRideConfig.java new file mode 100644 index 00000000..2693ea25 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/ride/AbstractRideConfig.java @@ -0,0 +1,94 @@ +package com.jverbruggen.jrides.config.ride; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.config.coaster.objects.InteractionEntitiesConfig; +import com.jverbruggen.jrides.config.coaster.objects.SoundsConfig; +import com.jverbruggen.jrides.config.coaster.objects.item.ItemStackConfig; +import com.jverbruggen.jrides.config.gates.GatesConfig; +import com.jverbruggen.jrides.models.properties.PlayerLocation; + +import java.util.List; + +public abstract class AbstractRideConfig extends BaseConfig { + private final String manifestVersion; + private final String identifier; + private final String displayName; + private final List displayDescription; + private final ItemStackConfig displayItem; + private final PlayerLocation warpLocation; + private final PlayerLocation customEjectLocation; + private final GatesConfig gates; + private final SoundsConfig soundsConfig; + private final boolean canExitDuringRide; + private final InteractionEntitiesConfig interactionEntities; + private final RideCounterMapConfigs rideCounterMapConfigs; + private final boolean debugMode; + + public AbstractRideConfig(String manifestVersion, String identifier, String displayName, List displayDescription, ItemStackConfig displayItem, PlayerLocation warpLocation, PlayerLocation customEjectLocation, GatesConfig gates, SoundsConfig soundsConfig, boolean canExitDuringRide, InteractionEntitiesConfig interactionEntities, RideCounterMapConfigs rideCounterMapConfigs, boolean debugMode) { + this.manifestVersion = manifestVersion; + this.identifier = identifier; + this.displayName = displayName; + this.displayDescription = displayDescription; + this.displayItem = displayItem; + this.warpLocation = warpLocation; + this.customEjectLocation = customEjectLocation; + this.gates = gates; + this.soundsConfig = soundsConfig; + this.canExitDuringRide = canExitDuringRide; + this.interactionEntities = interactionEntities; + this.rideCounterMapConfigs = rideCounterMapConfigs; + this.debugMode = debugMode; + } + + public String getManifestVersion() { + return manifestVersion; + } + + public String getIdentifier() { + return identifier; + } + + public String getDisplayName() { + return displayName; + } + + public List getDisplayDescription() { + return displayDescription; + } + + public ItemStackConfig getDisplayItem() { + return displayItem; + } + + public PlayerLocation getWarpLocation() { + return warpLocation; + } + + public PlayerLocation getCustomEjectLocation() { + return customEjectLocation; + } + + public SoundsConfig getSoundsConfig() { + return soundsConfig; + } + + public GatesConfig getGates() { + return gates; + } + + public boolean canExitDuringRide() { + return canExitDuringRide; + } + + public InteractionEntitiesConfig getInteractionEntities() { + return interactionEntities; + } + + public RideCounterMapConfigs getRideCounterMapConfigs() { + return rideCounterMapConfigs; + } + + public boolean isDebugMode() { + return debugMode; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/ride/RideCounterMapConfig.java b/src/main/java/com/jverbruggen/jrides/config/ride/RideCounterMapConfig.java new file mode 100644 index 00000000..d2ae6235 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/ride/RideCounterMapConfig.java @@ -0,0 +1,155 @@ +package com.jverbruggen.jrides.config.ride; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.config.ConfigManager; +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.models.map.ridecounter.RideCounterMapType; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import dev.cerus.maps.api.graphics.ColorCache; +import org.bukkit.configuration.ConfigurationSection; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class RideCounterMapConfig extends BaseConfig { + private final String rideCounterMapIdentifier; + private final RideCounterMapType rideCounterMapType; + private final List lines; + private final List mapIds; + private final List backgroundImages; + private final String lineFormat; + private final Integer rideNameLine; + private final Integer typeLine; + private final String typeText; + private final byte primaryColor; + private final byte secondaryColor; + private final byte tertiaryColor; + + public RideCounterMapConfig(String rideCounterMapIdentifier, RideCounterMapType rideCounterMapType, List lines, List mapIds, + List backgroundImages, String lineFormat, Integer rideNameLine, Integer typeLine, String typeText, + byte primaryColor, byte secondaryColor, byte tertiaryColor) { + this.rideCounterMapIdentifier = rideCounterMapIdentifier; + this.rideCounterMapType = rideCounterMapType; + this.lines = lines; + this.mapIds = mapIds; + this.backgroundImages = backgroundImages; + this.lineFormat = lineFormat; + this.rideNameLine = rideNameLine; + this.typeLine = typeLine; + this.typeText = typeText; + this.primaryColor = primaryColor; + this.secondaryColor = secondaryColor; + this.tertiaryColor = tertiaryColor; + } + + public RideCounterMapConfig() { + this(null, null, null, null, null, null, null, null, null, ColorCache.rgbToMap(0, 0, 0), ColorCache.rgbToMap(0, 0, 0), ColorCache.rgbToMap(0, 0, 0)); + } + + public String getRideCounterMapIdentifier() { + return rideCounterMapIdentifier; + } + + public RideCounterMapType getRideCounterMapType() { + return rideCounterMapType; + } + + public List getLines() { + return lines; + } + + public List getMapIds() { + return mapIds; + } + + public List getBackgroundImages() { + return backgroundImages; + } + + public String getLineFormat() { + return lineFormat; + } + + public Integer getRideNameLine() { + return rideNameLine; + } + + public Integer getTypeLine() { + return typeLine; + } + + public String getTypeText() { + return typeText; + } + + public byte getPrimaryColor() { + return primaryColor; + } + + public byte getSecondaryColor() { + return secondaryColor; + } + + public byte getTertiaryColor() { + return tertiaryColor; + } + + private static byte convertListToColorByte(List colorList) { + if(colorList == null || colorList.size() != 3) return ColorCache.rgbToMap(0, 0, 0); + return ColorCache.rgbToMap(colorList.get(0), colorList.get(1), colorList.get(2)); + } + + public static RideCounterMapConfig fromConfigurationSection(String rideIdentifier, ConfigurationSection configurationSection) { + if(configurationSection == null) return new RideCounterMapConfig(); + + ConfigManager configManager = ServiceProvider.getSingleton(ConfigManager.class); + + String rideCounterMapIdentifier = configurationSection.getName(); + RideCounterMapType rideCounterMapType = RideCounterMapType.valueOf(getString(configurationSection, "type", "top").toUpperCase()); + List lines = getIntegerList(configurationSection, "lines", new ArrayList<>()); + List mapIds = getIntegerList(configurationSection, "mapIds", new ArrayList<>()); + String lineFormat = getString(configurationSection, "lineFormat", "%RANK%. %NAME%: %COUNT%"); + Integer rideNameLine = getInt(configurationSection, "rideNameLine", -1); + Integer typeLine = getInt(configurationSection, "typeLine", -1); + + if(lines.isEmpty()) { + JRidesPlugin.getLogger().warning("No lines configured for " + rideIdentifier + " ridecounter map " + rideCounterMapIdentifier + ", the map will not be generated"); + } + + if(mapIds.isEmpty()) { + JRidesPlugin.getLogger().warning("No map ids configured for " + rideIdentifier + " ridecounter map " + rideCounterMapIdentifier + ", the map will not be generated"); + } + + String typeText = rideCounterMapType.toString().substring(0, 1).toUpperCase() + rideCounterMapType.toString().substring(1).toLowerCase() + " ridecounters"; + typeText = getString(configurationSection, "typeText", typeText); + + byte primaryColor = convertListToColorByte(getIntegerList(configurationSection, "primaryColor", null)); + byte secondaryColor = convertListToColorByte(getIntegerList(configurationSection, "secondaryColor", null)); + byte tertiaryColor = convertListToColorByte(getIntegerList(configurationSection, "tertiaryColor", null)); + + List backgroundImages = new ArrayList<>(); + + for(String backgroundImage : getStringList(configurationSection, "backgroundImages", new ArrayList<>())) { + String imagePath = JRidesPlugin.getBukkitPlugin().getDataFolder() + "/" + configManager.getCoasterFolder(rideIdentifier) + "/assets/" + backgroundImage; + File file = new File(imagePath); + if(!file.exists()) { + JRidesPlugin.getLogger().warning("Background image for " + rideIdentifier + " at " + imagePath + " does not exist, using default background"); + backgroundImages.add(null); + continue; + } + try { + backgroundImages.add(ImageIO.read(file)); + } catch(IOException e) { + JRidesPlugin.getLogger().warning("Background image for " + rideIdentifier + " at " + imagePath + " could not be read, using default background"); + backgroundImages.add(null); + } + } + + return new RideCounterMapConfig(rideCounterMapIdentifier, rideCounterMapType, lines, mapIds, backgroundImages, lineFormat, rideNameLine, typeLine, typeText, + primaryColor, secondaryColor, tertiaryColor); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/ride/RideCounterMapConfigs.java b/src/main/java/com/jverbruggen/jrides/config/ride/RideCounterMapConfigs.java new file mode 100644 index 00000000..f2228389 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/ride/RideCounterMapConfigs.java @@ -0,0 +1,38 @@ +package com.jverbruggen.jrides.config.ride; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.Map; +import java.util.stream.Collectors; + +public class RideCounterMapConfigs extends BaseConfig { + private final Map rideCounterMapConfigs; + + public RideCounterMapConfigs(Map rideCounterMapConfigs) { + this.rideCounterMapConfigs = rideCounterMapConfigs; + } + + public RideCounterMapConfigs() { + this(null); + } + + public Map getRideCounterMapConfigs() { + return rideCounterMapConfigs; + } + + public static RideCounterMapConfigs fromConfigurationSection(String rideIdentifier, ConfigurationSection configurationSection) { + if(configurationSection == null) return new RideCounterMapConfigs(); + + Map rideCounterMapConfigs = configurationSection.getKeys(false).stream().collect( + Collectors.toMap( + key -> key, + key -> RideCounterMapConfig.fromConfigurationSection(rideIdentifier, configurationSection.getConfigurationSection(key)) + ) + ); + + return new RideCounterMapConfigs(rideCounterMapConfigs); + } + + +} diff --git a/src/main/java/com/jverbruggen/jrides/config/ride/RideState.java b/src/main/java/com/jverbruggen/jrides/config/ride/RideState.java new file mode 100644 index 00000000..e9d37916 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/ride/RideState.java @@ -0,0 +1,146 @@ +package com.jverbruggen.jrides.config.ride; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.config.ConfigManager; +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.models.ride.state.OpenState; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.configuration.serialization.ConfigurationSerializable; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +enum RideType { + FLATRIDE, + COASTER +} + +public class RideState extends BaseConfig implements ConfigurationSerializable { + private final String rideIdentifier; + private OpenState openState; + private final RideType rideType; + + public RideState(String rideIdentifier, OpenState openState, RideType rideType) { + this.rideIdentifier = rideIdentifier; + this.openState = openState; + this.rideType = rideType; + } + + public OpenState getOpenState() { + return openState; + } + + public boolean setStateOpened(RideHandle rideHandle){ + if(openState == OpenState.DISABLED){ + JRidesPlugin.getLogger().severe("Cannot open a ride which has the DISABLED status"); + return false; + } + + if(openState.isOpen() || openState.isOpening()) + return false; + OpenState newState = openState.open(rideHandle); + boolean changed = newState != this.openState; + this.openState = newState; + return changed; + } + + public boolean setStateClosed(RideHandle rideHandle){ + if(openState == OpenState.DISABLED){ + JRidesPlugin.getLogger().severe("Cannot close a ride which has the DISABLED status"); + return false; + } + + if(!openState.isOpen()) + return false; + OpenState newState = openState.close(rideHandle); + boolean changed = newState != this.openState; + this.openState = newState; + return changed; + } + + public boolean setInactive(){ + this.openState = OpenState.INACTIVE; + return true; + } + + public boolean isInactive(){ + return this.openState == OpenState.INACTIVE || this.openState == OpenState.DISABLED; + } + + public boolean setStateFullyClosed(){ + if(openState != OpenState.TRANSITION_TO_CLOSE){ + return false; + } + this.openState = OpenState.CLOSED; + return true; + } + + public Map serialize() { + Map serialized = new HashMap<>(); + serialized.put("rideIdentifier", rideIdentifier); + serialized.put("rideType", rideType.toString()); + serialized.put("openState", openState.toString()); + + return serialized; + } + + public static RideState deserialize(Map config){ + String rideIdentifier = getString(config, "rideIdentifier"); + RideType rideType = RideType.valueOf(getString(config, "rideType")); + OpenState openState = OpenState.valueOf(getString(config, "openState", "MAINTENANCE")); + + return new RideState(rideIdentifier, openState, rideType); + } + + public boolean shouldLoadRide(){ + return openState != OpenState.DISABLED; + } + + public void save(){ + ConfigManager configManager = ServiceProvider.getSingleton(ConfigManager.class); + String fileName = switch (rideType) { + case FLATRIDE -> getFlatrideFileName(configManager, rideIdentifier); + case COASTER -> getCoasterFileName(configManager, rideIdentifier); + }; + + configManager.updateConfigFile(fileName, "state", this); + } + + public static RideState loadCoasterState(String rideIdentifier) { + ConfigManager configManager = ServiceProvider.getSingleton(ConfigManager.class); + String fileName = getCoasterFileName(configManager, rideIdentifier); + return load(rideIdentifier, fileName, RideType.COASTER); + } + + public static RideState loadFlatrideState(String rideIdentifier) { + ConfigManager configManager = ServiceProvider.getSingleton(ConfigManager.class); + String fileName = getFlatrideFileName(configManager, rideIdentifier); + return load(rideIdentifier, fileName, RideType.FLATRIDE); + } + + private static RideState load(String rideIdentifier, String fileName, RideType rideType){ + ConfigManager configManager = ServiceProvider.getSingleton(ConfigManager.class); + + Optional state = configManager.getConfigFileObject(fileName, "state", RideState.class); + + return state.orElseGet(() -> { + JRidesPlugin.getLogger().warning("Could not get ride state for " + rideIdentifier + ", creating new one"); + RideState newState = new RideState( + rideIdentifier, + OpenState.MAINTENANCE, + rideType); + configManager.updateConfigFile(fileName, "state", newState); + return newState; + }); + } + + private static String getCoasterFileName(ConfigManager configManager, String rideIdentifier){ + return configManager.getCoasterFolder(rideIdentifier) + "/" + rideIdentifier + ".state.yml"; + } + + private static String getFlatrideFileName(ConfigManager configManager, String rideIdentifier){ + return configManager.getFlatrideFolder(rideIdentifier) + "/" + rideIdentifier + ".state.yml"; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/ride/RidesConfig.java b/src/main/java/com/jverbruggen/jrides/config/ride/RidesConfig.java new file mode 100644 index 00000000..ee398077 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/ride/RidesConfig.java @@ -0,0 +1,27 @@ +package com.jverbruggen.jrides.config.ride; + +import org.bukkit.configuration.ConfigurationSection; + +import java.util.List; +import java.util.stream.Collectors; + +public class RidesConfig { + private List rides; + + public RidesConfig(List rides) { + this.rides = rides; + } + + public List getRides() { + return rides; + } + + public static RidesConfig fromConfigurationSection(ConfigurationSection configurationSection){ + List rides = configurationSection.getKeys(false) + .stream() + .map(i -> RidesConfigObject.fromConfigurationSection(configurationSection.getConfigurationSection(i))) + .collect(Collectors.toList()); + + return new RidesConfig(rides); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/ride/RidesConfigObject.java b/src/main/java/com/jverbruggen/jrides/config/ride/RidesConfigObject.java new file mode 100644 index 00000000..7299d1da --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/ride/RidesConfigObject.java @@ -0,0 +1,27 @@ +package com.jverbruggen.jrides.config.ride; + +import org.bukkit.configuration.ConfigurationSection; + +public class RidesConfigObject { + private String identifier; + private String type; + + public RidesConfigObject(String identifier, String type) { + this.identifier = identifier; + this.type = type; + } + + public String getIdentifier() { + return identifier; + } + + public String getType() { + return type; + } + + public static RidesConfigObject fromConfigurationSection(ConfigurationSection configurationSection){ + String identifier = configurationSection.getString("identifier"); + String type = configurationSection.getString("type"); + return new RidesConfigObject(identifier, type); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/BaseTriggerConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/BaseTriggerConfig.java new file mode 100644 index 00000000..3ac02f2f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/BaseTriggerConfig.java @@ -0,0 +1,16 @@ +package com.jverbruggen.jrides.config.trigger; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; + +public abstract class BaseTriggerConfig extends BaseConfig implements TriggerConfig { + protected TriggerType triggerType; + + public BaseTriggerConfig(TriggerType triggerType) { + this.triggerType = triggerType; + } + + @Override + public TriggerType getType() { + return triggerType; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/TriggerConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/TriggerConfig.java new file mode 100644 index 00000000..8dc3e52f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/TriggerConfig.java @@ -0,0 +1,8 @@ +package com.jverbruggen.jrides.config.trigger; + +import com.jverbruggen.jrides.effect.EffectTrigger; + +public interface TriggerConfig { + TriggerType getType(); + EffectTrigger createTrigger(); +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/TriggerConfigFactory.java b/src/main/java/com/jverbruggen/jrides/config/trigger/TriggerConfigFactory.java new file mode 100644 index 00000000..7ffb7373 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/TriggerConfigFactory.java @@ -0,0 +1,69 @@ +package com.jverbruggen.jrides.config.trigger; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.config.trigger.cart.CartRestraintTriggerConfig; +import com.jverbruggen.jrides.config.trigger.entity.MultiEntityMovementConfig; +import com.jverbruggen.jrides.config.trigger.external.CommandAsPlayerTriggerConfig; +import com.jverbruggen.jrides.config.trigger.external.CommandForPlayerTriggerConfig; +import com.jverbruggen.jrides.config.trigger.external.CommandTriggerConfig; +import com.jverbruggen.jrides.config.trigger.external.ExternalTriggerConfig; +import com.jverbruggen.jrides.config.trigger.external.animation.AnimatedJavaTriggerConfig; +import com.jverbruggen.jrides.config.trigger.music.MusicTriggerConfig; +import com.jverbruggen.jrides.config.trigger.structure.StructureConfig; +import com.jverbruggen.jrides.config.trigger.train.EjectTriggerConfig; +import com.jverbruggen.jrides.config.trigger.train.ResetTriggerConfig; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.HashMap; +import java.util.Map; + +public class TriggerConfigFactory { + private final Map triggerConfigList; + + public TriggerConfigFactory() { + this.triggerConfigList = new HashMap<>(); + } + + public TriggerConfig fromConfigurationSection(String rideIdentifier, String effectName, ConfigurationSection configurationSection){ + if(configurationSection == null) throw new RuntimeException("Trigger configuration was null for effect " + effectName); + + TriggerType type = TriggerType.fromString(configurationSection.getString("type")); + TriggerConfig triggerConfig; + String mapKey = rideIdentifier + ":" + effectName; + if(triggerConfigList.containsKey(mapKey)){ + JRidesPlugin.getLogger().warning("Duplicate trigger identifier in triggers of ride " + rideIdentifier + ": '" + effectName + "'. Ignoring new one."); + return triggerConfigList.get(mapKey); + } + + triggerConfig = switch (type) { + case RESET -> + ResetTriggerConfig.fromConfigurationSection(configurationSection); + case MUSIC -> + MusicTriggerConfig.fromConfigurationSection(configurationSection); + case COMMAND -> + CommandTriggerConfig.fromConfigurationSection(configurationSection); + case EJECT -> + EjectTriggerConfig.fromConfigurationSection(configurationSection); + case COMMAND_FOR_PLAYER -> + CommandForPlayerTriggerConfig.fromConfigurationSection(configurationSection); + case COMMAND_AS_PLAYER -> + CommandAsPlayerTriggerConfig.fromConfigurationSection(configurationSection); + case ANIMATION_SEQUENCE -> + MultiEntityMovementConfig.fromConfigurationSection(configurationSection); + case ANIMATED_JAVA -> + AnimatedJavaTriggerConfig.fromConfigurationSection(configurationSection); + case STRUCTURE -> + StructureConfig.fromConfigurationSection(configurationSection); + case EXTERNAL_EVENT -> + ExternalTriggerConfig.fromConfigurationSection(configurationSection); + case CART_ROTATE -> + throw new RuntimeException("Not supported yet cart rotate"); + case CART_RESTRAINT -> + CartRestraintTriggerConfig.fromConfigurationSection(configurationSection); + }; + + triggerConfigList.put(mapKey, triggerConfig); + + return triggerConfig; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/TriggerType.java b/src/main/java/com/jverbruggen/jrides/config/trigger/TriggerType.java new file mode 100644 index 00000000..f05468e4 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/TriggerType.java @@ -0,0 +1,38 @@ +package com.jverbruggen.jrides.config.trigger; + +import javax.annotation.Nullable; + +public enum TriggerType { + RESET, + MUSIC, + COMMAND, + EJECT, + COMMAND_FOR_PLAYER, + COMMAND_AS_PLAYER, + EXTERNAL_EVENT, + ANIMATION_SEQUENCE, + ANIMATED_JAVA, + STRUCTURE, + CART_ROTATE, + CART_RESTRAINT; + + + public static TriggerType fromString(@Nullable String typeString){ + if(typeString == null) throw new RuntimeException("Cannot convert null to TriggerType"); + + if(typeString.equalsIgnoreCase("reset")) return RESET; + else if(typeString.equalsIgnoreCase("music")) return MUSIC; + else if(typeString.equalsIgnoreCase("command")) return COMMAND; + else if(typeString.equalsIgnoreCase("eject")) return EJECT; + else if(typeString.equalsIgnoreCase("command-for-player")) return COMMAND_FOR_PLAYER; + else if(typeString.equalsIgnoreCase("command-as-player")) return COMMAND_AS_PLAYER; + else if(typeString.equalsIgnoreCase("external")) return EXTERNAL_EVENT; + else if(typeString.equalsIgnoreCase("animation-sequence")) return ANIMATION_SEQUENCE; + else if(typeString.equalsIgnoreCase("animated-java")) return ANIMATED_JAVA; + else if(typeString.equalsIgnoreCase("structure")) return STRUCTURE; + else if(typeString.equalsIgnoreCase("cart-rotate")) return CART_ROTATE; + else if(typeString.equalsIgnoreCase("cart-restraint")) return CART_RESTRAINT; + + throw new RuntimeException("Trigger type " + typeString + " is not supported"); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/cart/CartRestraintTriggerConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/cart/CartRestraintTriggerConfig.java new file mode 100644 index 00000000..7b4dfb6a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/cart/CartRestraintTriggerConfig.java @@ -0,0 +1,27 @@ +package com.jverbruggen.jrides.config.trigger.cart; + +import com.jverbruggen.jrides.config.trigger.BaseTriggerConfig; +import com.jverbruggen.jrides.config.trigger.TriggerType; +import com.jverbruggen.jrides.effect.EffectTrigger; +import com.jverbruggen.jrides.effect.cart.CartRestraintEffectTrigger; +import org.bukkit.configuration.ConfigurationSection; + +public class CartRestraintTriggerConfig extends BaseTriggerConfig { + public final boolean locked; + + public CartRestraintTriggerConfig(boolean locked) { + super(TriggerType.CART_RESTRAINT); + this.locked = locked; + } + + public static CartRestraintTriggerConfig fromConfigurationSection(ConfigurationSection configurationSection){ + boolean locked = getBoolean(configurationSection, "locked"); + + return new CartRestraintTriggerConfig(locked); + } + + @Override + public EffectTrigger createTrigger() { + return new CartRestraintEffectTrigger(locked); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/cart/CartRotationTriggerConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/cart/CartRotationTriggerConfig.java new file mode 100644 index 00000000..68d9b655 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/cart/CartRotationTriggerConfig.java @@ -0,0 +1,39 @@ +package com.jverbruggen.jrides.config.trigger.cart; + +import com.jverbruggen.jrides.config.trigger.BaseTriggerConfig; +import com.jverbruggen.jrides.config.trigger.TriggerType; +import com.jverbruggen.jrides.effect.EffectTrigger; +import com.jverbruggen.jrides.effect.cart.rotation.CartRotationEffectTrigger; +import com.jverbruggen.jrides.models.math.Vector3; +import org.bukkit.configuration.ConfigurationSection; + +public class CartRotationTriggerConfig extends BaseTriggerConfig { + private final Vector3 rotation; + private final int animationTicks; + + public CartRotationTriggerConfig(Vector3 rotation, int animationTicks) { + super(TriggerType.CART_ROTATE); + this.rotation = rotation; + this.animationTicks = animationTicks; + } + + public Vector3 getRotation() { + return rotation; + } + + public int getAnimationTicks() { + return animationTicks; + } + + public static CartRotationTriggerConfig fromConfigurationSection(ConfigurationSection configurationSection){ + Vector3 rotation = Vector3.fromDoubleList(getDoubleList(configurationSection, "rotation")); + int animationTicks = getInt(configurationSection, "animationTicks", 20); + + return new CartRotationTriggerConfig(rotation, animationTicks); + } + + @Override + public EffectTrigger createTrigger() { + return new CartRotationEffectTrigger(getRotation(), getAnimationTicks()); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/entity/EntityContinuousMovementConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/entity/EntityContinuousMovementConfig.java new file mode 100644 index 00000000..cd8559ef --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/entity/EntityContinuousMovementConfig.java @@ -0,0 +1,65 @@ +package com.jverbruggen.jrides.config.trigger.entity; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.effect.entity.EntityContinuousMovementEffectTrigger; +import com.jverbruggen.jrides.effect.entity.EntityMovementTrigger; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import org.bukkit.configuration.ConfigurationSection; + +public class EntityContinuousMovementConfig extends BaseConfig implements EntityMovementConfig { + private final Vector3 initialLocation; + private final Vector3 initialRotation; + private final boolean resetOnStart; + + private final Vector3 locationDelta; + private final Vector3 rotationDelta; + private final int animationTimeTicks; + private final int delayTicks; + + public EntityContinuousMovementConfig(Vector3 initialLocation, Vector3 initialRotation, boolean resetOnStart, Vector3 locationDelta, Vector3 rotationDelta, int animationTimeTicks, int delayTicks) { + this.initialLocation = initialLocation; + this.initialRotation = initialRotation; + this.resetOnStart = resetOnStart; + this.locationDelta = locationDelta; + this.rotationDelta = rotationDelta; + this.animationTimeTicks = animationTimeTicks; + this.delayTicks = delayTicks; + } + + public static EntityContinuousMovementConfig fromConfigurationSection(ConfigurationSection configurationSection){ + Vector3 initialLocation = Vector3.fromDoubleList(getDoubleList(configurationSection, "initialLocation", null)); + Vector3 initialRotation = Vector3.fromDoubleList(getDoubleList(configurationSection, "initialRotation", null)); + Vector3 locationDelta = Vector3.fromDoubleList(getDoubleList(configurationSection, "locationDelta", null)); + Vector3 rotationDelta = Vector3.fromDoubleList(getDoubleList(configurationSection, "rotationDelta", null)); + int animationTimeTicks = getInt(configurationSection, "animationTimeTicks", 20); + int delayTicks = getInt(configurationSection, "delayTicks", 0); + boolean resetOnStart = getBoolean(configurationSection, "resetOnStart", true); + + return new EntityContinuousMovementConfig(initialLocation, initialRotation, resetOnStart, locationDelta, rotationDelta, animationTimeTicks, delayTicks); + } + + @Override + public EntityMovementTrigger createTrigger(VirtualEntity virtualEntity) { + Quaternion initialRotation = null; + if(this.initialRotation != null){ + initialRotation = Quaternion.fromAnglesVector(this.initialRotation); + virtualEntity.setRotation(initialRotation); + } + + Quaternion rotationDelta = Quaternion.fromAnglesVector(this.rotationDelta); + + return new EntityContinuousMovementEffectTrigger(virtualEntity, initialLocation, initialRotation, resetOnStart, locationDelta, rotationDelta, animationTimeTicks, delayTicks); + } + + @Override + public Vector3 getInitialPosition() { + return initialLocation; + } + + @Override + public Vector3 getInitialRotation() { + return initialRotation; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/entity/EntityFromToMovementConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/entity/EntityFromToMovementConfig.java new file mode 100644 index 00000000..07077bf3 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/entity/EntityFromToMovementConfig.java @@ -0,0 +1,97 @@ +package com.jverbruggen.jrides.config.trigger.entity; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.effect.entity.EntityFromToMovementEffectTrigger; +import com.jverbruggen.jrides.effect.entity.EntityMovementTrigger; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import org.bukkit.configuration.ConfigurationSection; + +public class EntityFromToMovementConfig extends BaseConfig implements EntityMovementConfig { + private final Vector3 locationFrom; + private final Vector3 locationTo; + private final Vector3 rotationFrom; + private final Vector3 rotationTo; + private final int animationTimeTicks; + private final int delayTicks; + + private final boolean locationHasDelta; + private final boolean rotationHasDelta; + + public EntityFromToMovementConfig(Vector3 locationFrom, Vector3 locationTo, Vector3 rotationFrom, Vector3 rotationTo, int animationTimeTicks, int delayTicks) { + this.locationFrom = locationFrom; + this.locationTo = locationTo; + this.rotationFrom = rotationFrom; + this.rotationTo = rotationTo; + this.animationTimeTicks = animationTimeTicks; + this.delayTicks = delayTicks; + this.locationHasDelta = locationFrom != null && locationTo != null && locationTo.distanceSquared(locationFrom) > 0.01; + this.rotationHasDelta = rotationFrom != null && rotationTo != null && rotationTo.distanceSquared(rotationFrom) > 0.01; + } + + public Vector3 getLocationFrom() { + return locationFrom; + } + + public Vector3 getLocationTo() { + return locationTo; + } + + public Vector3 getRotationFrom() { + return rotationFrom; + } + + public Vector3 getRotationTo() { + return rotationTo; + } + + public int getAnimationTimeTicks() { + return animationTimeTicks; + } + + public boolean isLocationHasDelta() { + return locationHasDelta; + } + + public boolean isRotationHasDelta() { + return rotationHasDelta; + } + + public static EntityFromToMovementConfig fromConfigurationSection(ConfigurationSection configurationSection){ + Vector3 locationFrom = Vector3.fromDoubleList(getDoubleList(configurationSection, "locationFrom", null)); + Vector3 locationTo = Vector3.fromDoubleList(getDoubleList(configurationSection, "locationTo", null)); + Vector3 rotationFrom = Vector3.fromDoubleList(getDoubleList(configurationSection, "rotationFrom", null)); + Vector3 rotationTo = Vector3.fromDoubleList(getDoubleList(configurationSection, "rotationTo", null)); + int animationTimeTicks = getInt(configurationSection, "animationTimeTicks", 20); + int delayTicks = getInt(configurationSection, "delayTicks", 0); + + return new EntityFromToMovementConfig(locationFrom, locationTo, rotationFrom, rotationTo, animationTimeTicks, delayTicks); + } + + @Override + public EntityMovementTrigger createTrigger(VirtualEntity virtualEntity) { + boolean hasLocationDelta = isLocationHasDelta(); + boolean hasRotationDelta = isRotationHasDelta(); + + Vector3 locationFrom = hasLocationDelta ? getLocationFrom() : null; + Vector3 locationTo = hasLocationDelta ? getLocationTo() : null; + + Quaternion rotationFrom = hasRotationDelta ? Quaternion.fromAnglesVector(getRotationFrom()) : null; + Quaternion rotationTo = hasRotationDelta ? Quaternion.fromAnglesVector(getRotationTo()) : null; + + int animationTimeTicks = getAnimationTimeTicks(); + + return new EntityFromToMovementEffectTrigger(virtualEntity, locationFrom, locationTo, rotationFrom, rotationTo, animationTimeTicks, delayTicks); + } + + @Override + public Vector3 getInitialPosition() { + return locationFrom; + } + + @Override + public Vector3 getInitialRotation() { + return rotationFrom; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/entity/EntityMovementCollectionConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/entity/EntityMovementCollectionConfig.java new file mode 100644 index 00000000..78a48fee --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/entity/EntityMovementCollectionConfig.java @@ -0,0 +1,112 @@ +package com.jverbruggen.jrides.config.trigger.entity; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.config.coaster.objects.item.ItemConfig; +import com.jverbruggen.jrides.effect.entity.EntityMovementTrigger; +import com.jverbruggen.jrides.effect.train.SequenceTrainEffectTrigger; +import com.jverbruggen.jrides.effect.train.TrainEffectTrigger; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.LocRot; +import com.jverbruggen.jrides.state.viewport.ViewportManager; +import org.bukkit.configuration.ConfigurationSection; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +public class EntityMovementCollectionConfig extends BaseConfig { + @SuppressWarnings("unused") + private final String identifier; //TODO: integrate + private final ItemConfig itemConfig; + private final Vector3 spawnLocation; + private final Vector3 spawnRotation; + private final List entityMovementConfigs; + + public EntityMovementCollectionConfig(String identifier, ItemConfig itemConfig, Vector3 spawnLocation, Vector3 spawnRotation, List entityMovementConfigs) { + this.identifier = identifier; + this.itemConfig = itemConfig; + this.spawnLocation = spawnLocation; + this.spawnRotation = spawnRotation; + this.entityMovementConfigs = entityMovementConfigs; + } + + static EntityMovementCollectionConfig fromConfigurationSection(String identifier, @Nullable ConfigurationSection configurationSection){ + if(configurationSection == null) return null; + + ConfigurationSection animationConfigurationSection = configurationSection.getConfigurationSection("animation"); + + List entityMovements = new ArrayList<>(); + if(animationConfigurationSection != null){ + Set keys = animationConfigurationSection.getKeys(false); + for(String key : keys){ + EntityMovementConfig movementConfig = getMovementConfig(identifier, animationConfigurationSection.getConfigurationSection(key)); + if(movementConfig == null) continue; + + entityMovements.add(movementConfig); + } + } + + Vector3 spawnLocation = Vector3.fromDoubleList(getDoubleList(configurationSection, "spawnLocation", null)); + Vector3 spawnRotation = Vector3.fromDoubleList(getDoubleList(configurationSection, "spawnRotation", null)); + ItemConfig itemConfig = ItemConfig.fromConfigurationSection(configurationSection); + + return new EntityMovementCollectionConfig(identifier, itemConfig, spawnLocation, spawnRotation, entityMovements); + } + + static EntityMovementConfig getMovementConfig(String identifier, @Nullable ConfigurationSection configurationSection){ + if(configurationSection == null) return null; + + String movementType = getString(configurationSection, "type", null); + if(movementType != null && movementType.equalsIgnoreCase("projectile")){ + return EntityProjectileConfig.fromConfigurationSection(configurationSection); + } + + if(configurationSection.contains("locationFrom") || configurationSection.contains("rotationFrom")){ + return EntityFromToMovementConfig.fromConfigurationSection(configurationSection); + }else if(configurationSection.contains("locationDelta") || configurationSection.contains("rotationDelta")){ + return EntityContinuousMovementConfig.fromConfigurationSection(configurationSection); + }else if(configurationSection.contains("item")){ + return ReplaceItemConfig.fromConfigurationSection(configurationSection); + } + + throw new RuntimeException("Unknown entity movement in " + identifier); + } + + private LocRot getSpawnLocation(){ + if(spawnLocation != null) { + return LocRot.fromLocationRotation(spawnLocation, spawnRotation); + } + + if(entityMovementConfigs.size() == 0) throw new RuntimeException("Cannot get spawn location"); + + LocRot initialLocation = null; + for(EntityMovementConfig config : entityMovementConfigs){ + Vector3 possibleLocation = config.getInitialPosition(); + if(possibleLocation != null){ + initialLocation = new LocRot(possibleLocation, config.getInitialRotation()); + break; + } + } + + if(initialLocation == null) throw new RuntimeException("Animation does not support initial location, cannot spawn entity"); + + return initialLocation; + } + + public TrainEffectTrigger createTrigger(ViewportManager viewportManager) { + LocRot spawnLocation = getSpawnLocation(); + Quaternion rotation = Quaternion.fromAnglesVector(spawnLocation.rotation()); + VirtualEntity virtualEntity = itemConfig.spawnEntity(viewportManager, spawnLocation.location(), rotation, null); + virtualEntity.setRotation(Quaternion.fromAnglesVector(spawnLocation.rotation())); + + List triggerSequence = entityMovementConfigs.stream() + .map(c -> c.createTrigger(virtualEntity)) + .collect(Collectors.toList()); + + return new SequenceTrainEffectTrigger(triggerSequence); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/entity/EntityMovementConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/entity/EntityMovementConfig.java new file mode 100644 index 00000000..2dd3ca78 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/entity/EntityMovementConfig.java @@ -0,0 +1,11 @@ +package com.jverbruggen.jrides.config.trigger.entity; + +import com.jverbruggen.jrides.effect.entity.EntityMovementTrigger; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Vector3; + +public interface EntityMovementConfig { + EntityMovementTrigger createTrigger(VirtualEntity virtualEntity); + Vector3 getInitialPosition(); + Vector3 getInitialRotation(); +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/entity/EntityProjectileConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/entity/EntityProjectileConfig.java new file mode 100644 index 00000000..0e427efd --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/entity/EntityProjectileConfig.java @@ -0,0 +1,75 @@ +package com.jverbruggen.jrides.config.trigger.entity; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.effect.entity.EntityMovementTrigger; +import com.jverbruggen.jrides.effect.entity.EntityProjectileEffect; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import org.bukkit.configuration.ConfigurationSection; + +public class EntityProjectileConfig extends BaseConfig implements EntityMovementConfig { + private final Vector3 initialPosition; + private final Vector3 initialRotation; + + private final Vector3 initialPositionalVelocity; + private final Vector3 initialRotationalVelocity; + private final Vector3 positionalAcceleration; + private final Vector3 rotationalAcceleration; + private final boolean resetOnStart; + private final int animationTimeTicks; + private final int delayTicks; + + public EntityProjectileConfig(Vector3 initialPosition, Vector3 initialRotation, Vector3 initialPositionalVelocity, Vector3 initialRotationalVelocity, + Vector3 positionalAcceleration, Vector3 rotationalAcceleration, boolean resetOnStart, int animationTimeTicks, int delayTicks) { + this.initialPosition = initialPosition; + this.initialRotation = initialRotation; + this.initialPositionalVelocity = initialPositionalVelocity; + this.initialRotationalVelocity = initialRotationalVelocity; + this.positionalAcceleration = positionalAcceleration; + this.rotationalAcceleration = rotationalAcceleration; + this.resetOnStart = resetOnStart; + this.animationTimeTicks = animationTimeTicks; + this.delayTicks = delayTicks; + } + + public static EntityProjectileConfig fromConfigurationSection(ConfigurationSection configurationSection){ + Vector3 initialPosition = Vector3.fromDoubleList(getDoubleList(configurationSection, "initialPosition")); + Vector3 initialRotation = Vector3.fromDoubleList(getDoubleList(configurationSection, "initialRotation", createDoubleList(0, 0, 0))); + Vector3 initialPositionalVelocity = Vector3.fromDoubleList(getDoubleList(configurationSection, "initialPositionalVelocity")); + Vector3 initialRotationalVelocity = Vector3.fromDoubleList(getDoubleList(configurationSection, "initialRotationalVelocity", createDoubleList(0, 0, 0))); + Vector3 positionalAcceleration = Vector3.fromDoubleList(getDoubleList(configurationSection, "positionalAcceleration", createDoubleList(0, -0.08,0))); + Vector3 rotationalAcceleration = Vector3.fromDoubleList(getDoubleList(configurationSection, "rotationalAcceleration", createDoubleList(0, 0, 0))); + int animationTimeTicks = getInt(configurationSection, "animationTimeTicks", 60); + int delayTicks = getInt(configurationSection, "delayTicks", 0); + boolean resetOnStart = getBoolean(configurationSection, "resetOnStart", true); + + return new EntityProjectileConfig(initialPosition, initialRotation, initialPositionalVelocity, initialRotationalVelocity, + positionalAcceleration, rotationalAcceleration, resetOnStart, animationTimeTicks, delayTicks); + } + + @Override + public EntityMovementTrigger createTrigger(VirtualEntity virtualEntity) { + Quaternion initialRotation = Quaternion.fromAnglesVector(this.initialRotation); + Quaternion initialRotationalVelocity = Quaternion.fromAnglesVector(this.initialRotationalVelocity); + Quaternion rotationalAcceleration = Quaternion.fromAnglesVector(this.rotationalAcceleration); + + virtualEntity.setRendered(false); + virtualEntity.setLocation(initialPosition); + virtualEntity.setRotation(initialRotation); + + return new EntityProjectileEffect(virtualEntity, resetOnStart, initialPosition, initialRotation, initialPositionalVelocity, initialRotationalVelocity, + positionalAcceleration, rotationalAcceleration, animationTimeTicks, delayTicks); + } + + @Override + public Vector3 getInitialPosition() { + return initialPosition; + } + + @Override + public Vector3 getInitialRotation() { + return initialRotation; + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/entity/MultiEntityMovementConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/entity/MultiEntityMovementConfig.java new file mode 100644 index 00000000..b2f54825 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/entity/MultiEntityMovementConfig.java @@ -0,0 +1,63 @@ +package com.jverbruggen.jrides.config.trigger.entity; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.config.trigger.BaseTriggerConfig; +import com.jverbruggen.jrides.config.trigger.TriggerType; +import com.jverbruggen.jrides.effect.entity.MultipleEffectExecutorTrigger; +import com.jverbruggen.jrides.effect.train.TrainEffectTrigger; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.viewport.ViewportManager; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +public class MultiEntityMovementConfig extends BaseTriggerConfig { + private final List entityMovements; + + public MultiEntityMovementConfig(List entityMovements) { + super(TriggerType.ANIMATION_SEQUENCE); + this.entityMovements = entityMovements; + } + + public List getEntityMovements() { + return entityMovements; + } + + public List createTriggers(ViewportManager viewportManager){ + List armorstandMovements = new ArrayList<>(); + for(EntityMovementCollectionConfig entityMovementConfig : getEntityMovements()) { + armorstandMovements.add(entityMovementConfig.createTrigger(viewportManager)); + } + + return armorstandMovements; + } + + public static MultiEntityMovementConfig fromConfigurationSection(ConfigurationSection configurationSection){ + ConfigurationSection entitiesSection = configurationSection.getConfigurationSection("entities"); + if(entitiesSection == null) throw new RuntimeException("Trigger section needs 'entities' key"); + + Set entityIdentifiers = entitiesSection.getKeys(false); + + List entityMovements = new ArrayList<>(); + for(String identifier : entityIdentifiers){ + EntityMovementCollectionConfig entityMovementCollection = EntityMovementCollectionConfig.fromConfigurationSection(identifier, entitiesSection.getConfigurationSection(identifier)); + if(entityMovementCollection == null){ + JRidesPlugin.getLogger().warning("Entity movement " + identifier + " was null"); + continue; + } + entityMovements.add(entityMovementCollection); + } + + return new MultiEntityMovementConfig(entityMovements); + } + + @Override + public TrainEffectTrigger createTrigger() { + ViewportManager viewportManager = ServiceProvider.getSingleton(ViewportManager.class); + List entityMovementTriggers = createTriggers(viewportManager); + + return new MultipleEffectExecutorTrigger(entityMovementTriggers); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/entity/ReplaceItemConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/entity/ReplaceItemConfig.java new file mode 100644 index 00000000..9b913519 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/entity/ReplaceItemConfig.java @@ -0,0 +1,43 @@ +package com.jverbruggen.jrides.config.trigger.entity; + +import com.jverbruggen.jrides.config.coaster.objects.BaseConfig; +import com.jverbruggen.jrides.config.coaster.objects.item.ItemStackConfig; +import com.jverbruggen.jrides.effect.entity.EntityMovementTrigger; +import com.jverbruggen.jrides.effect.entity.ReplaceItemEffectTrigger; +import com.jverbruggen.jrides.models.entity.TrainModelItem; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Vector3; +import org.bukkit.configuration.ConfigurationSection; + +public class ReplaceItemConfig extends BaseConfig implements EntityMovementConfig { + private final ItemStackConfig itemStackConfig; + private final int delayTicks; + + public ReplaceItemConfig(ItemStackConfig itemStackConfig, int delayTicks) { + this.itemStackConfig = itemStackConfig; + this.delayTicks = delayTicks; + } + + @Override + public EntityMovementTrigger createTrigger(VirtualEntity virtualEntity) { + TrainModelItem trainModelItem = new TrainModelItem(itemStackConfig.createItemStack()); + return new ReplaceItemEffectTrigger(trainModelItem, virtualEntity, delayTicks); + } + + @Override + public Vector3 getInitialPosition() { + return null; + } + + @Override + public Vector3 getInitialRotation() { + return null; + } + + public static ReplaceItemConfig fromConfigurationSection(ConfigurationSection configurationSection) { + ItemStackConfig itemStackConfig = ItemStackConfig.fromConfigurationSection(configurationSection.getConfigurationSection("item")); + int delayTicks = getInt(configurationSection, "delayTicks", 0); + + return new ReplaceItemConfig(itemStackConfig, delayTicks); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/external/CommandAsPlayerTriggerConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/external/CommandAsPlayerTriggerConfig.java new file mode 100644 index 00000000..1c487322 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/external/CommandAsPlayerTriggerConfig.java @@ -0,0 +1,27 @@ +package com.jverbruggen.jrides.config.trigger.external; + +import com.jverbruggen.jrides.config.trigger.BaseTriggerConfig; +import com.jverbruggen.jrides.config.trigger.TriggerType; +import com.jverbruggen.jrides.effect.EffectTrigger; +import com.jverbruggen.jrides.effect.external.CommandAsPlayerEffectTrigger; +import org.bukkit.configuration.ConfigurationSection; + +public class CommandAsPlayerTriggerConfig extends BaseTriggerConfig { + private final String command; + + public CommandAsPlayerTriggerConfig(String command) { + super(TriggerType.COMMAND_AS_PLAYER); + this.command = command; + } + + public static CommandAsPlayerTriggerConfig fromConfigurationSection(ConfigurationSection configurationSection){ + String command = getString(configurationSection, "command"); + + return new CommandAsPlayerTriggerConfig(command); + } + + @Override + public EffectTrigger createTrigger() { + return new CommandAsPlayerEffectTrigger(command); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/external/CommandForPlayerTriggerConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/external/CommandForPlayerTriggerConfig.java new file mode 100644 index 00000000..af163111 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/external/CommandForPlayerTriggerConfig.java @@ -0,0 +1,27 @@ +package com.jverbruggen.jrides.config.trigger.external; + +import com.jverbruggen.jrides.config.trigger.BaseTriggerConfig; +import com.jverbruggen.jrides.config.trigger.TriggerType; +import com.jverbruggen.jrides.effect.EffectTrigger; +import com.jverbruggen.jrides.effect.external.CommandForPlayerEffectTrigger; +import org.bukkit.configuration.ConfigurationSection; + +public class CommandForPlayerTriggerConfig extends BaseTriggerConfig { + private final String command; + + public CommandForPlayerTriggerConfig(String command) { + super(TriggerType.COMMAND_FOR_PLAYER); + this.command = command; + } + + public static CommandForPlayerTriggerConfig fromConfigurationSection(ConfigurationSection configurationSection){ + String command = getString(configurationSection, "command"); + + return new CommandForPlayerTriggerConfig(command); + } + + @Override + public EffectTrigger createTrigger() { + return new CommandForPlayerEffectTrigger(command); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/external/CommandTriggerConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/external/CommandTriggerConfig.java new file mode 100644 index 00000000..11d4b4e1 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/external/CommandTriggerConfig.java @@ -0,0 +1,27 @@ +package com.jverbruggen.jrides.config.trigger.external; + +import com.jverbruggen.jrides.config.trigger.BaseTriggerConfig; +import com.jverbruggen.jrides.config.trigger.TriggerType; +import com.jverbruggen.jrides.effect.EffectTrigger; +import com.jverbruggen.jrides.effect.external.CommandEffectTrigger; +import org.bukkit.configuration.ConfigurationSection; + +public class CommandTriggerConfig extends BaseTriggerConfig { + private final String command; + + public CommandTriggerConfig(String command) { + super(TriggerType.COMMAND); + this.command = command; + } + + public static CommandTriggerConfig fromConfigurationSection(ConfigurationSection configurationSection){ + String command = getString(configurationSection, "command"); + + return new CommandTriggerConfig(command); + } + + @Override + public EffectTrigger createTrigger() { + return new CommandEffectTrigger(command); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/external/ExternalTriggerConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/external/ExternalTriggerConfig.java new file mode 100644 index 00000000..e0052736 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/external/ExternalTriggerConfig.java @@ -0,0 +1,37 @@ +package com.jverbruggen.jrides.config.trigger.external; + +import com.jverbruggen.jrides.config.trigger.BaseTriggerConfig; +import com.jverbruggen.jrides.config.trigger.TriggerType; +import com.jverbruggen.jrides.effect.train.TrainEffectTrigger; +import com.jverbruggen.jrides.effect.train.external.ExternalEffectTrigger; +import org.bukkit.configuration.ConfigurationSection; + +import javax.annotation.Nonnull; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +public class ExternalTriggerConfig extends BaseTriggerConfig { + private final Map data; + + public ExternalTriggerConfig(Map data) { + super(TriggerType.EXTERNAL_EVENT); + + this.data = data; + } + + public static ExternalTriggerConfig fromConfigurationSection(@Nonnull ConfigurationSection configurationSection){ + Map data = configurationSection.getKeys(false) + .stream() + .collect(Collectors.toMap( + k -> k, + k -> Objects.requireNonNull(configurationSection.getString(k)))); + + return new ExternalTriggerConfig(data); + } + + @Override + public TrainEffectTrigger createTrigger() { + return new ExternalEffectTrigger(data); + } +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/external/animation/AnimatedJavaTriggerConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/external/animation/AnimatedJavaTriggerConfig.java new file mode 100644 index 00000000..344bd56e --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/external/animation/AnimatedJavaTriggerConfig.java @@ -0,0 +1,42 @@ +package com.jverbruggen.jrides.config.trigger.external.animation; + +import com.jverbruggen.jrides.animator.animatedjava.AnimatedJavaExecutor; +import com.jverbruggen.jrides.config.trigger.BaseTriggerConfig; +import com.jverbruggen.jrides.config.trigger.TriggerType; +import com.jverbruggen.jrides.effect.EffectTrigger; +import com.jverbruggen.jrides.effect.external.animation.AnimatedJavaEffectTrigger; +import com.jverbruggen.jrides.models.math.Vector3; +import org.bukkit.configuration.ConfigurationSection; + +public class AnimatedJavaTriggerConfig extends BaseTriggerConfig { + private final Vector3 location; + private final String rigName; + private final String animationName; + private final String rootEntitySelectorTag; + private final int despawnAfterTicks; + + public AnimatedJavaTriggerConfig(Vector3 location, String rigName, String animationName, String rootEntitySelectorTag, int despawnAfterTicks) { + super(TriggerType.ANIMATED_JAVA); + this.location = location; + this.rigName = rigName; + this.animationName = animationName; + this.rootEntitySelectorTag = rootEntitySelectorTag; + this.despawnAfterTicks = despawnAfterTicks; + } + + public static AnimatedJavaTriggerConfig fromConfigurationSection(ConfigurationSection configurationSection){ + Vector3 location = Vector3.fromDoubleList(getDoubleList(configurationSection, "location")); + String rigName = getString(configurationSection, "rigName"); + String animationName = getString(configurationSection, "animationName"); + String rootEntitySelectorTag = getString(configurationSection, "rootEntitySelectorTag"); + int despawnAfterTicks = getInt(configurationSection, "despawnOnFinish", -1); + + return new AnimatedJavaTriggerConfig(location, rigName, animationName, rootEntitySelectorTag, despawnAfterTicks); + } + + @Override + public EffectTrigger createTrigger() { + AnimatedJavaExecutor executor = new AnimatedJavaExecutor(rootEntitySelectorTag, rigName, location); + return new AnimatedJavaEffectTrigger(executor, animationName, despawnAfterTicks); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/music/MusicTriggerConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/music/MusicTriggerConfig.java new file mode 100644 index 00000000..627ce911 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/music/MusicTriggerConfig.java @@ -0,0 +1,46 @@ +package com.jverbruggen.jrides.config.trigger.music; + +import com.jverbruggen.jrides.config.trigger.BaseTriggerConfig; +import com.jverbruggen.jrides.config.trigger.TriggerType; +import com.jverbruggen.jrides.effect.train.TrainEffectTrigger; +import com.jverbruggen.jrides.effect.train.music.ExternalMusicEffectTrigger; +import org.bukkit.configuration.ConfigurationSection; + +public class MusicTriggerConfig extends BaseTriggerConfig { + private final MusicTriggerConfigHandler handler; + private final String resource; + private final String descriptor; + + public MusicTriggerConfig(MusicTriggerConfigHandler handler, String resource, String descriptor) { + super(TriggerType.MUSIC); + this.handler = handler; + this.resource = resource; + this.descriptor = descriptor; + } + + @SuppressWarnings("unused") + public MusicTriggerConfigHandler getHandler() { + return handler; + } + + public String getDescriptor() { + return descriptor; + } + + public String getResource() { + return resource; + } + + public static MusicTriggerConfig fromConfigurationSection(ConfigurationSection configurationSection){ + MusicTriggerConfigHandler handler = MusicTriggerConfigHandler.fromString(getString(configurationSection, "handler")); + String resource = getString(configurationSection, "resource"); + String descriptor = getString(configurationSection, "descriptor", "default"); + + return new MusicTriggerConfig(handler, resource, descriptor); + } + + @Override + public TrainEffectTrigger createTrigger() { + return new ExternalMusicEffectTrigger(getResource(), getDescriptor()); + } +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/music/MusicTriggerConfigHandler.java b/src/main/java/com/jverbruggen/jrides/config/trigger/music/MusicTriggerConfigHandler.java new file mode 100644 index 00000000..3612fb74 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/music/MusicTriggerConfigHandler.java @@ -0,0 +1,14 @@ +package com.jverbruggen.jrides.config.trigger.music; + +public enum MusicTriggerConfigHandler { + EVENT, + RESOURCE_PACK, + SOME_AUDIO_PLUGIN; + + public static MusicTriggerConfigHandler fromString(String value){ + if(value.equalsIgnoreCase("event")) return EVENT; + else if(value.equalsIgnoreCase("resource_pack")) return RESOURCE_PACK; + + throw new RuntimeException("Music trigger type " + value + " is not supported"); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/structure/StructureConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/structure/StructureConfig.java new file mode 100644 index 00000000..d91d2bcf --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/structure/StructureConfig.java @@ -0,0 +1,46 @@ +package com.jverbruggen.jrides.config.trigger.structure; + +import com.jverbruggen.jrides.config.trigger.BaseTriggerConfig; +import com.jverbruggen.jrides.config.trigger.TriggerType; +import com.jverbruggen.jrides.effect.EffectTrigger; +import com.jverbruggen.jrides.effect.structure.StructureEffectTrigger; +import com.jverbruggen.jrides.models.math.Vector3; +import org.bukkit.configuration.ConfigurationSection; + +public class StructureConfig extends BaseTriggerConfig { + private final String structureIdentifier; + private final Vector3 position; + private final int delayTicks; + + public StructureConfig(String structureIdentifier, Vector3 position, int delayTicks) { + super(TriggerType.STRUCTURE); + this.structureIdentifier = structureIdentifier; + this.position = position; + this.delayTicks = delayTicks; + } + + public String getStructureIdentifier() { + return structureIdentifier; + } + + public Vector3 getPosition() { + return position; + } + + public int getDelayTicks() { + return delayTicks; + } + + public static StructureConfig fromConfigurationSection(ConfigurationSection configurationSection){ + String structureIdentifier = getString(configurationSection, "structureIdentifier"); + Vector3 position = Vector3.fromDoubleList(getDoubleList(configurationSection, "position")); + int delayTicks = getInt(configurationSection, "delayTicks", 0); + + return new StructureConfig(structureIdentifier, position, delayTicks); + } + + @Override + public EffectTrigger createTrigger() { + return StructureEffectTrigger.createStructureEffectTrigger(getDelayTicks(), getPosition(), getStructureIdentifier()); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/train/EjectTriggerConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/train/EjectTriggerConfig.java new file mode 100644 index 00000000..0241666a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/train/EjectTriggerConfig.java @@ -0,0 +1,27 @@ +package com.jverbruggen.jrides.config.trigger.train; + +import com.jverbruggen.jrides.config.trigger.BaseTriggerConfig; +import com.jverbruggen.jrides.config.trigger.TriggerType; +import com.jverbruggen.jrides.effect.EffectTrigger; +import com.jverbruggen.jrides.effect.train.EjectEffectTrigger; +import org.bukkit.configuration.ConfigurationSection; + +public class EjectTriggerConfig extends BaseTriggerConfig { + private final boolean asFinished; + + public EjectTriggerConfig(boolean asFinished) { + super(TriggerType.EJECT); + this.asFinished = asFinished; + } + + public static EjectTriggerConfig fromConfigurationSection(ConfigurationSection configurationSection){ + boolean asFinished = getBoolean(configurationSection, "asFinished", true); + + return new EjectTriggerConfig(asFinished); + } + + @Override + public EffectTrigger createTrigger() { + return new EjectEffectTrigger(asFinished); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/trigger/train/ResetTriggerConfig.java b/src/main/java/com/jverbruggen/jrides/config/trigger/train/ResetTriggerConfig.java new file mode 100644 index 00000000..636f5056 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/trigger/train/ResetTriggerConfig.java @@ -0,0 +1,23 @@ + +package com.jverbruggen.jrides.config.trigger.train; + +import com.jverbruggen.jrides.config.trigger.BaseTriggerConfig; +import com.jverbruggen.jrides.config.trigger.TriggerType; +import com.jverbruggen.jrides.effect.EffectTrigger; +import com.jverbruggen.jrides.effect.train.ResetEffectTrigger; +import org.bukkit.configuration.ConfigurationSection; + +public class ResetTriggerConfig extends BaseTriggerConfig { + public ResetTriggerConfig() { + super(TriggerType.RESET); + } + + public static ResetTriggerConfig fromConfigurationSection(ConfigurationSection configurationSection){ + return new ResetTriggerConfig(); + } + + @Override + public EffectTrigger createTrigger() { + return new ResetEffectTrigger(); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/utils/integersupplier/CycleIntegerSupplier.java b/src/main/java/com/jverbruggen/jrides/config/utils/integersupplier/CycleIntegerSupplier.java new file mode 100644 index 00000000..fce4a148 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/utils/integersupplier/CycleIntegerSupplier.java @@ -0,0 +1,21 @@ +package com.jverbruggen.jrides.config.utils.integersupplier; + +import java.util.List; +import java.util.function.Supplier; + +public class CycleIntegerSupplier implements Supplier { + private final List cycle; + private int pointer; + + public CycleIntegerSupplier(List cycle) { + this.cycle = cycle; + this.pointer = 0; + } + + @Override + public Integer get() { + int newPointer = pointer; + pointer = (pointer + 1) % cycle.size(); + return cycle.get(newPointer); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/utils/integersupplier/RandomIntegerSupplier.java b/src/main/java/com/jverbruggen/jrides/config/utils/integersupplier/RandomIntegerSupplier.java new file mode 100644 index 00000000..4239d798 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/utils/integersupplier/RandomIntegerSupplier.java @@ -0,0 +1,18 @@ +package com.jverbruggen.jrides.config.utils.integersupplier; + +import java.util.function.Supplier; + +public class RandomIntegerSupplier implements Supplier { + private final int lowerRange; + private final int upperRange; + + public RandomIntegerSupplier(int lowerRange, int upperRange) { + this.lowerRange = lowerRange; + this.upperRange = upperRange; + } + + @Override + public Integer get() { + return (int)(Math.random() * (upperRange - lowerRange)) + lowerRange; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/config/utils/integersupplier/SimpleIntegerSupplier.java b/src/main/java/com/jverbruggen/jrides/config/utils/integersupplier/SimpleIntegerSupplier.java new file mode 100644 index 00000000..7ce3b396 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/config/utils/integersupplier/SimpleIntegerSupplier.java @@ -0,0 +1,16 @@ +package com.jverbruggen.jrides.config.utils.integersupplier; + +import java.util.function.Supplier; + +public class SimpleIntegerSupplier implements Supplier { + private final int value; + + public SimpleIntegerSupplier(int value) { + this.value = value; + } + + @Override + public Integer get() { + return value; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/ControlAction.java b/src/main/java/com/jverbruggen/jrides/control/ControlAction.java new file mode 100644 index 00000000..e566535c --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/ControlAction.java @@ -0,0 +1,7 @@ +package com.jverbruggen.jrides.control; + +public enum ControlAction { + DISPATCH, + GATES, + RESTRAINTS +} diff --git a/src/main/java/com/jverbruggen/jrides/control/DispatchLock.java b/src/main/java/com/jverbruggen/jrides/control/DispatchLock.java new file mode 100644 index 00000000..286d8922 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/DispatchLock.java @@ -0,0 +1,62 @@ +package com.jverbruggen.jrides.control; + +import java.util.List; +import java.util.function.Consumer; + +/** + * A dispatch lock is used to see if a ride is ready for dispatch. + * Several factors can be at play when dispatching a ride, each + * of them able to prevent the vehicle from being dispatched. + * I.e. restraints, gates, or if a minimum waiting time has passed + *
+ * If the DispatchLock is in the locked state, it prevents the ride from dispatching. + * If the DispatchLock is in the unlocked state, it is OK with the ride dispatching. + */ +public interface DispatchLock { + String getDescription(); + + /** + * Set lock to the locked state, preventing dispatch from happening. + */ + void lock(); + + /** + * Set lock to unlocked state, allowing dispatch to happen. + */ + void unlock(); + + /** + * Set status of the lock, which is visible to the player + * and use as communication of what is preventing the ride from being dispatched. + * @param status Explanation of why the lock is in the locked state. + */ + void setStatus(String status); + void setDebugStatus(String status); + + /** + * Lock has no objection to dispatching. + * @return True if it allows for dispatch, False if it should prevent the ride from dispatching. + */ + boolean isUnlocked(); + + /** + * Set DispatchLock to explicit state + * @param locked True if the ride should be prevented from being dispatched. + */ + void setLocked(boolean locked); + + /** + * Get a problem list of everything that is preventing the ride from being dispatched. + * In a simple DispatchLock implementation, this list would be of length 1. + * @param detailLevel Depth of how detailed the message should be (used in nested locks) + * @param debug Debug mode = True should be used for administrative or debugging purposes. + * @return A list of all problems + */ + List getProblems(int detailLevel, boolean debug); + + /** + * Register a consumer to updates to the lock. + * @param eventListener A consumer function that receives the lock with updated state, whenever a state change happens. + */ + void addEventListener(Consumer eventListener); +} diff --git a/src/main/java/com/jverbruggen/jrides/control/DispatchLockCollection.java b/src/main/java/com/jverbruggen/jrides/control/DispatchLockCollection.java new file mode 100644 index 00000000..f961b353 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/DispatchLockCollection.java @@ -0,0 +1,182 @@ +package com.jverbruggen.jrides.control; + +import org.bukkit.ChatColor; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.function.Consumer; + +public class DispatchLockCollection implements DispatchLock { + private final String description; + private final List locks; + private final List> lockEventListeners; + private final List> unlockEventListeners; + private DispatchLockCollection parentCollection; + private boolean noticeSelfAsProblem; + private @Nullable String statusCached; + private @Nullable String debugStatusCached; + + public DispatchLockCollection(String description) { + this.description = description; + this.locks = new ArrayList<>(); + this.lockEventListeners = new ArrayList<>(); + this.unlockEventListeners = new ArrayList<>(); + this.parentCollection = null; + this.noticeSelfAsProblem = false; + this.statusCached = null; + this.debugStatusCached = null; + } + + public DispatchLockCollection(String description, DispatchLockCollection parentCollection) { + this.description = description; + this.locks = new ArrayList<>(); + this.lockEventListeners = new ArrayList<>(); + this.unlockEventListeners = new ArrayList<>(); + this.noticeSelfAsProblem = true; + + this.setParentCollection(parentCollection); + this.statusCached = null; + this.debugStatusCached = null; + } + + public void addLockEventListener(Consumer lockEventListener){ + lockEventListeners.add(lockEventListener); + } + + public void addUnlockEventListener(Consumer unlockEventListener){ + unlockEventListeners.add(unlockEventListener); + } + + public void setParentCollection(DispatchLockCollection parentCollection) { + this.parentCollection = parentCollection; + + this.parentCollection.addDispatchLock(this); + } + + public DispatchLockCollection getParentCollection() { + return parentCollection; + } + + public void addEventListener(Consumer eventListener){ + addLockEventListener(eventListener); + addUnlockEventListener(eventListener); + } + + public void addDispatchLock(DispatchLock dispatchLock){ + if(this.locks.contains(dispatchLock)) return; + + this.locks.add(dispatchLock); + } + + public boolean allUnlocked(){ + return locks.stream().allMatch(DispatchLock::isUnlocked); + } + + @Override + public List getProblems(int detailLevel, boolean debug){ + List problems = new ArrayList<>(); + if(noticeSelfAsProblem && !this.isUnlocked()) + problems.add(ChatColor.GRAY + "- " + this.getDescription()); + + if(detailLevel <= 1 && noticeSelfAsProblem) return problems; + int newDetailLevel = detailLevel; + if(noticeSelfAsProblem) newDetailLevel--; + + for(DispatchLock lock : locks){ + if(!lock.isUnlocked()){ + problems.addAll(lock.getProblems(newDetailLevel, debug)); + } + } + + return problems; + } + + public void onLock(DispatchLock lock){ + lockEventListeners.forEach(l -> l.accept(lock)); + if(parentCollection != null) parentCollection.onLock(lock); + } + + public void onUnlock(DispatchLock lock){ + unlockEventListeners.forEach(l -> l.accept(lock)); + if(parentCollection != null) parentCollection.onUnlock(lock); + } + + public void onStatusUpdate(DispatchLock lock){ + unlockEventListeners.forEach(l -> l.accept(lock)); + if(parentCollection != null) parentCollection.onStatusUpdate(lock); + } + + public Consumer toStatusListener(){ + return this::onStatusUpdate; + } + + @Override + public String getDescription() { + return description; + } + + @Override + public void lock() { + locks.forEach(DispatchLock::lock); + } + + @Override + public void unlock() { + locks.forEach(DispatchLock::unlock); + } + + @Override + public void setStatus(String status) { + if(!Objects.equals(statusCached, status)){ + statusCached = status; + unlockEventListeners.forEach(l -> l.accept(this)); + } + } + + @Override + public void setDebugStatus(String status) { + if(!Objects.equals(debugStatusCached, status)){ + debugStatusCached = status; + unlockEventListeners.forEach(l -> l.accept(this)); + } + } + + @Override + public boolean isUnlocked() { + return allUnlocked(); + } + + @Override + public void setLocked(boolean locked) { + locks.forEach(l -> l.setLocked(locked)); + } + + @Override + public String toString() { + return "DispatchLockCollection{" + + "description='" + description + '\'' + + ", locks=" + locks + + ", statusCached='" + statusCached + '\'' + + '}'; + } + + public static DispatchLockCollection makeHybrid(String description, DispatchLockCollection... dispatchLockCollections){ + DispatchLockCollection hybrid = new DispatchLockCollection(description); + + for(DispatchLockCollection dispatchLockCollection : dispatchLockCollections){ + hybrid.addDispatchLock(dispatchLockCollection); + + for(Consumer lockEventListener : dispatchLockCollection.lockEventListeners){ + hybrid.addLockEventListener(lockEventListener); + } + + for(Consumer unlockEventListener : dispatchLockCollection.unlockEventListeners){ + hybrid.addUnlockEventListener(unlockEventListener); + } + } + + return hybrid; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/SimpleDispatchLock.java b/src/main/java/com/jverbruggen/jrides/control/SimpleDispatchLock.java new file mode 100644 index 00000000..1bf31de6 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/SimpleDispatchLock.java @@ -0,0 +1,102 @@ +package com.jverbruggen.jrides.control; + +import org.bukkit.ChatColor; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +public class SimpleDispatchLock implements DispatchLock { + private DispatchLockCollection parentCollection; + private boolean locked; + private String description; + private final List> eventListeners; + private String status; + private String debugStatus; + + /** + * Simple implementation of a DispatchLock + * @param parentCollection the parent collection that it is part of. + * @param description Description of what the lock is blocking for. + * @param initLocked Whether the lock should initially be locked (preventing the ride from dispatching) or unlocked (allowing dispatching to happen) + */ + public SimpleDispatchLock(DispatchLockCollection parentCollection, String description, boolean initLocked) { + this.parentCollection = parentCollection; + this.description = description; + this.locked = initLocked; + this.eventListeners = new ArrayList<>(); + this.status = ""; + this.debugStatus = ""; + + this.parentCollection.addDispatchLock(this); + } + + @Override + public String getDescription() { + return description; + } + + @Override + public void setStatus(String status) { + this.status = status; + eventListeners.forEach(l -> l.accept(this)); + parentCollection.onStatusUpdate(this); + } + + @Override + public void setDebugStatus(String status) { + debugStatus = status; + } + + @Override + public void lock(){ + if(locked) return; + locked = true; + parentCollection.onLock(this); + eventListeners.forEach(l -> l.accept(this)); + } + + @Override + public void unlock(){ + if(!locked) return; + locked = false; + parentCollection.onUnlock(this); + eventListeners.forEach(l -> l.accept(this)); + } + + @Override + public boolean isUnlocked(){ + return !locked; + } + + @Override + public void setLocked(boolean locked) { + if(locked) lock(); + else unlock(); + } + + @Override + public List getProblems(int detailLevel, boolean debug) { + if(detailLevel <= 0) return List.of(); + + String statusSpec = status.equals("") ? "" : " (" + status + ")"; + if(debug) statusSpec += debugStatus.equals("") ? "" : " [" + debugStatus + "]"; + + return List.of(ChatColor.GRAY + "- " + this.getDescription() + statusSpec); + } + + @Override + public void addEventListener(Consumer eventListener) { + eventListeners.add(eventListener); + } + + @Override + public String toString() { + return "SimpleDispatchLock{" + + "locked=" + locked + + ", description='" + description + '\'' + + ", status='" + status + '\'' + + ", debugStatus='" + debugStatus + '\'' + + '}'; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/controller/DualRideController.java b/src/main/java/com/jverbruggen/jrides/control/controller/DualRideController.java new file mode 100644 index 00000000..ab63ad62 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/controller/DualRideController.java @@ -0,0 +1,26 @@ +package com.jverbruggen.jrides.control.controller; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.control.controller.base.SingularRideController; +import com.jverbruggen.jrides.control.trigger.TriggerContext; + +public class DualRideController extends SingularRideController implements RideController { + private TriggerContext leftStationTriggerContext; + private TriggerContext rightStationTriggerContext; + + public DualRideController(TriggerContext leftStationTriggerContext, TriggerContext rightStationTriggerContext, RideHandle rideHandle) { + this.leftStationTriggerContext = leftStationTriggerContext; + this.rightStationTriggerContext = rightStationTriggerContext; + + this.changeMode(this.getControlModeFactory().getForWithoutOperator(rideHandle)); + this.setRideHandle(rideHandle); + } + + public TriggerContext getLeftStationTriggerContext() { + return leftStationTriggerContext; + } + + public TriggerContext getRightStationTriggerContext() { + return rightStationTriggerContext; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/controller/RideController.java b/src/main/java/com/jverbruggen/jrides/control/controller/RideController.java new file mode 100644 index 00000000..fd17720a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/controller/RideController.java @@ -0,0 +1,36 @@ +package com.jverbruggen.jrides.control.controller; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.control.controlmode.ControlMode; +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.ride.Ride; +import com.jverbruggen.jrides.models.ride.StationHandle; +import com.jverbruggen.jrides.models.ride.coaster.train.Vehicle; + +public interface RideController { + RideHandle getRideHandle(); + void setRideHandle(RideHandle rideHandle); + + TriggerContext getTriggerContext(); + + void changeMode(ControlMode newControlMode); + + Ride getRide(); + + void onVehicleArrive(Vehicle vehicle, StationHandle stationHandle); + + void onVehicleDepart(Vehicle vehicle, StationHandle stationHandle); + + ControlMode getControlMode(); + void setControlMode(ControlMode controlMode); + + boolean setOperator(Player player); + + Player getOperator(); + + boolean isActive(); + void setActive(boolean active); + boolean supportsMenu(); + +} diff --git a/src/main/java/com/jverbruggen/jrides/control/controller/RideControllerFactory.java b/src/main/java/com/jverbruggen/jrides/control/controller/RideControllerFactory.java new file mode 100644 index 00000000..5d433ec9 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/controller/RideControllerFactory.java @@ -0,0 +1,58 @@ +package com.jverbruggen.jrides.control.controller; + +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.config.coaster.objects.ControllerConfig; +import com.jverbruggen.jrides.config.coaster.objects.controller.DualControllerSpecConfig; +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.exception.CoasterLoadException; +import com.jverbruggen.jrides.models.ride.CoasterStationHandle; + +public class RideControllerFactory { + public RideController createCoasterController(CoasterHandle coasterHandle, ControllerConfig controllerConfig) throws CoasterLoadException { + if(!coasterHandle.hasStation()) + return createVoidCoasterController(coasterHandle); + + if(controllerConfig == null || controllerConfig.getType().equalsIgnoreCase(ControllerConfig.CONTROLLER_DEFAULT)) + return createDefaultCoasterController(coasterHandle); + + String type = controllerConfig.getType(); + if(type.equalsIgnoreCase(ControllerConfig.CONTROLLER_ALTERNATE)) + return createDualCoasterController(coasterHandle, controllerConfig.getAlternateControllerSpecConfig()); + if(type.equalsIgnoreCase(ControllerConfig.CONTROLLER_SIMULTANEOUS)) + return createDualCoasterController(coasterHandle, controllerConfig.getAlternateControllerSpecConfig()); + + throw new RuntimeException("Ride controller type " + type + " is not supported"); + } + + private RideController createDualCoasterController(CoasterHandle coasterHandle, DualControllerSpecConfig dualControllerSpecConfig) { + String stationLeftName = dualControllerSpecConfig.getStationLeft(); + String stationRightName = dualControllerSpecConfig.getStationRight(); + + CoasterStationHandle stationHandleLeft = coasterHandle.getStationHandle(stationLeftName); + CoasterStationHandle stationHandleRight = coasterHandle.getStationHandle(stationRightName); + + if(stationHandleLeft == null) throw new RuntimeException("Could not find station " + stationLeftName + " to make ride controller"); + else if(stationHandleRight == null) throw new RuntimeException("Could not find station " + stationRightName + " to make ride controller"); + + return new DualRideController(stationHandleLeft.getTriggerContext(), stationHandleRight.getTriggerContext(), coasterHandle); + } + + private RideController createDefaultCoasterController(CoasterHandle coasterHandle) throws CoasterLoadException { + CoasterStationHandle stationHandle = coasterHandle.getStationHandle(0); + if(stationHandle == null){ + throw new CoasterLoadException("Ride controller for " + coasterHandle.getRide().getIdentifier() + " could not be created because no station was available"); + } + + return new SimpleRideController(coasterHandle, stationHandle.getTriggerContext()); + } + + private RideController createVoidCoasterController(CoasterHandle coasterHandle){ + return SimpleRideController.createVoid(coasterHandle); + + } + + public RideController createFlatRideController(FlatRideHandle flatRideHandle){ + return new SimpleRideController(flatRideHandle, flatRideHandle.getFirstTriggerContext()); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/controller/SimpleRideController.java b/src/main/java/com/jverbruggen/jrides/control/controller/SimpleRideController.java new file mode 100644 index 00000000..905dc260 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/controller/SimpleRideController.java @@ -0,0 +1,37 @@ +package com.jverbruggen.jrides.control.controller; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.control.controller.base.SingularRideController; +import com.jverbruggen.jrides.control.controlmode.ControlMode; +import com.jverbruggen.jrides.control.controlmode.factory.ControlModeFactory; +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.models.ride.CoasterStationHandle; +import com.jverbruggen.jrides.models.ride.StationHandle; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +public class SimpleRideController extends SingularRideController implements RideController { + private final TriggerContext triggerContext; + + public SimpleRideController(RideHandle rideHandle, TriggerContext triggerContext) { + super(); + this.triggerContext = triggerContext; + this.changeMode(this.getControlModeFactory().getForWithoutOperator(rideHandle)); + + this.setRideHandle(rideHandle); + } + + @Override + public TriggerContext getTriggerContext() { + return triggerContext; + } + + public static SimpleRideController createVoid(RideHandle rideHandle){ + SimpleRideController simpleRideController = new SimpleRideController(rideHandle, new TriggerContext( + null, null, null, null, null + )); + + simpleRideController.supportsMenu = false; + + return simpleRideController; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/controller/base/BaseRideController.java b/src/main/java/com/jverbruggen/jrides/control/controller/base/BaseRideController.java new file mode 100644 index 00000000..a865a420 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/controller/base/BaseRideController.java @@ -0,0 +1,28 @@ +package com.jverbruggen.jrides.control.controller.base; + +import com.jverbruggen.jrides.control.controller.RideController; + +public abstract class BaseRideController implements RideController { + private boolean active; + protected boolean supportsMenu; + + public BaseRideController() { + this.active = false; + this.supportsMenu = true; + } + + @Override + public boolean isActive() { + return active; + } + + @Override + public void setActive(boolean active) { + this.active = active; + } + + @Override + public boolean supportsMenu() { + return supportsMenu; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/controller/base/SingularRideController.java b/src/main/java/com/jverbruggen/jrides/control/controller/base/SingularRideController.java new file mode 100644 index 00000000..fe49fe39 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/controller/base/SingularRideController.java @@ -0,0 +1,110 @@ +package com.jverbruggen.jrides.control.controller.base; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.control.controller.RideController; +import com.jverbruggen.jrides.control.controlmode.ControlMode; +import com.jverbruggen.jrides.control.controlmode.factory.ControlModeFactory; +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.ride.Ride; +import com.jverbruggen.jrides.models.ride.StationHandle; +import com.jverbruggen.jrides.models.ride.coaster.train.Vehicle; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; + +public abstract class SingularRideController extends BaseRideController implements RideController { + private final ControlModeFactory controlModeFactory; + private ControlMode controlMode; + private RideHandle rideHandle; + + protected SingularRideController() { + this.controlModeFactory = ServiceProvider.getSingleton(ControlModeFactory.class); + } + + @Override + public RideHandle getRideHandle() { + return rideHandle; + } + + @Override + public TriggerContext getTriggerContext() { + return getRideHandle().getFirstTriggerContext(); + } + + @Override + public void setRideHandle(RideHandle rideHandle) { + this.rideHandle = rideHandle; + + if(getControlMode() == null) return; + getControlMode().setTriggerContext(getTriggerContext()); + setActive(true); + } + + + @Override + public Ride getRide() { + return rideHandle.getRide(); + } + + @Override + public ControlMode getControlMode() { + return controlMode; + } + + @Override + public void setControlMode(ControlMode controlMode) { + this.controlMode = controlMode; + } + + @Override + public boolean setOperator(Player player){ + Player previousOperator = this.getControlMode().getOperator(); + if(previousOperator == player) return true; + + boolean result = true; + + if(player == null){ + result = this.getControlMode().setOperator(null); + this.changeMode(this.controlModeFactory.getForWithoutOperator(this.rideHandle)); + }else if(previousOperator == null){ + this.changeMode(this.controlModeFactory.getForWithOperator(this.rideHandle)); + result = this.getControlMode().setOperator(player); + } + return result; + } + + @Override + public void changeMode(ControlMode newControlMode){ + if(newControlMode == null){ + JRidesPlugin.getLogger().severe("Control mode of ride controller of " + getRide().getIdentifier() + " was set to null. Ride is now inactive"); + setActive(false); + }else{ + if(getRideHandle() != null){ + newControlMode.setTriggerContext(getTriggerContext()); + setActive(true); + } + } + + setControlMode(newControlMode); + } + + @Override + public Player getOperator(){ + return this.getControlMode().getOperator(); + } + + public ControlModeFactory getControlModeFactory() { + return controlModeFactory; + } + + + @Override + public void onVehicleArrive(Vehicle vehicle, StationHandle stationHandle){ + getControlMode().onVehicleArrive(vehicle, stationHandle); + } + + @Override + public void onVehicleDepart(Vehicle train, StationHandle stationHandle) { + getControlMode().onVehicleDepart(train, stationHandle); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/controlmode/AutomaticAlternateMode.java b/src/main/java/com/jverbruggen/jrides/control/controlmode/AutomaticAlternateMode.java new file mode 100644 index 00000000..4a669234 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/controlmode/AutomaticAlternateMode.java @@ -0,0 +1,74 @@ +package com.jverbruggen.jrides.control.controlmode; + + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.control.ControlAction; +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.properties.MinMaxWaitingTimer; +import com.jverbruggen.jrides.models.ride.StationHandle; +import com.jverbruggen.jrides.models.ride.coaster.train.Vehicle; + +import java.util.List; + +public class AutomaticAlternateMode implements ControlMode{ + private int stationHandlePointer; + private final List stationHandles; + private final ControlMode automaticMode; + + public AutomaticAlternateMode(ControlMode automaticMode, List stationHandles) { + this.stationHandlePointer = 0; + this.stationHandles = stationHandles; + this.automaticMode = automaticMode; + } + + private void incrementStationHandlePointer(){ + stationHandlePointer = (stationHandlePointer+1) % stationHandles.size(); + + TriggerContext triggerContext = stationHandles.get(stationHandlePointer).getTriggerContext(); + automaticMode.setTriggerContext(triggerContext); + } + + @Override + public void tick() { + automaticMode.tick(); + } + + @Override + public void onVehicleArrive(Vehicle vehicle, StationHandle stationHandle) { + automaticMode.onVehicleArrive(vehicle, stationHandle); + } + + @Override + public void onVehicleDepart(Vehicle vehicle, StationHandle stationHandle) { + automaticMode.onVehicleDepart(vehicle, stationHandle); + incrementStationHandlePointer(); + } + + @Override + public boolean setOperator(Player player) { + return automaticMode.setOperator(player); + } + + @Override + public boolean allowsAction(ControlAction action, Player player) { + return automaticMode.allowsAction(action, player); + } + + @Override + public MinMaxWaitingTimer getWaitingTimer() { + return automaticMode.getWaitingTimer(); + } + + @Override + public Player getOperator() { + return automaticMode.getOperator(); + } + + @Override + public void setTriggerContext(TriggerContext triggerContext) { +// throw new RuntimeException("Not implemented"); + automaticMode.setTriggerContext(triggerContext); + JRidesPlugin.getLogger().warning("Set trigger context on alternate mode (unhandled)"); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/controlmode/AutomaticMode.java b/src/main/java/com/jverbruggen/jrides/control/controlmode/AutomaticMode.java new file mode 100644 index 00000000..4cf19686 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/controlmode/AutomaticMode.java @@ -0,0 +1,81 @@ +package com.jverbruggen.jrides.control.controlmode; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.control.ControlAction; +import com.jverbruggen.jrides.control.DispatchLockCollection; +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.properties.DebounceCall; +import com.jverbruggen.jrides.models.properties.MinMaxWaitingTimer; +import com.jverbruggen.jrides.models.ride.StationHandle; +import com.jverbruggen.jrides.models.ride.coaster.train.Vehicle; + +public class AutomaticMode extends BaseControlMode implements ControlMode{ + private final DebounceCall dispatchDebounce; + + public AutomaticMode(RideHandle rideHandle, TriggerContext triggerContext, MinMaxWaitingTimer waitingTimer) { + super(rideHandle, triggerContext, waitingTimer); + + this.dispatchDebounce = new DebounceCall(20); + } + + @Override + public void tick() { + super.tick(); + + stationTick(); + } + + void stationTick(){ + if(!rideHandle.isOpen()) return; + + MinMaxWaitingTimer waitingTimer = getWaitingTimer(); + + StationHandle stationHandle = triggerContext.getParentStation(); + Vehicle stationaryVehicle = stationHandle.getStationaryVehicle(); + if(stationaryVehicle == null) return; + + int visualTime = waitingTimer.getVisualDispatchTime(waitingTimer.timeUntilPreferredWaitingTime()); + waitingTimer.sendTimeWaitingNotification(stationaryVehicle.getPassengers(), visualTime); + + if(!waitingTimer.reachedFunction()) return; + triggerContext.getGateTrigger().setGatesState(true); + triggerContext.getRestraintTrigger().setRestraintsState(true); + + DispatchLockCollection dispatchLockCollection = triggerContext.getDispatchLockCollection(); + if(dispatchLockCollection != null && !dispatchLockCollection.allUnlocked()) return; + + dispatchDebounce.run(() -> triggerContext.getDispatchTrigger().execute(null)); + } + + @Override + public void onVehicleArrive(Vehicle vehicle, StationHandle stationHandle) { + super.onVehicleArrive(vehicle, stationHandle); + + dispatchDebounce.reset(); + stationHandle.openEntryGates(); + } + + @Override + public void onVehicleDepart(Vehicle vehicle, StationHandle stationHandle) { + super.onVehicleDepart(vehicle, stationHandle); + + dispatchDebounce.reset(); + stationHandle.closeEntryGates(); + } + + @Override + public boolean setOperator(Player player) { + return false; + } + + @Override + public boolean allowsAction(ControlAction action, Player player) { + return false; + } + + @Override + public Player getOperator() { + return null; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/controlmode/BaseControlMode.java b/src/main/java/com/jverbruggen/jrides/control/controlmode/BaseControlMode.java new file mode 100644 index 00000000..b2d4511d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/controlmode/BaseControlMode.java @@ -0,0 +1,124 @@ +package com.jverbruggen.jrides.control.controlmode; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.control.ControlAction; +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.language.LanguageFileTag; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.properties.MinMaxWaitingTimer; +import com.jverbruggen.jrides.models.ride.StationHandle; +import com.jverbruggen.jrides.models.ride.coaster.train.Vehicle; + +public abstract class BaseControlMode implements ControlMode { + protected final RideHandle rideHandle; + protected final LanguageFile languageFile; + protected TriggerContext triggerContext; + protected MinMaxWaitingTimer waitingTimer; + protected Player operator; + + protected final long tickInterval; + + private int tickIntervalState; + + protected BaseControlMode(RideHandle rideHandle, TriggerContext triggerContext, MinMaxWaitingTimer waitingTimer) { + this.rideHandle = rideHandle; + this.languageFile = JRidesPlugin.getLanguageFile(); + this.triggerContext = triggerContext; + + this.waitingTimer = waitingTimer; + + this.tickInterval = 5L; + this.tickIntervalState = 0; + this.operator = null; + } + + @Override + public void tick() { + if(tickIntervalState < tickInterval-1){ + tickIntervalState++; + return; + } + tickIntervalState = 0; + + incrementWaitingTimer(); + } + + protected void incrementWaitingTimer(){ + if(triggerContext.getVehiclePresentLock().isUnlocked()) waitingTimer.increment(tickInterval); + } + + /** + * Kicks current operator out of control mode. + * Should only be used in combination with RideController, + * since the RideController manages switching between + * control modes. + * @param newOperator + * @return + */ + @Override + public boolean setOperator(Player newOperator) { + if(newOperator == null){ + if(operator == null) return true; + + removeCurrentOperator(); + return true; + } + if(newOperator.equals(operator)){ + return true; + } + if(operator == null){ + operator = newOperator; + return true; + } + if(newOperator.getBukkitPlayer().hasPermission(Permissions.ELEVATED_OPERATOR_OVERRIDE)){ + removeCurrentOperator(); + languageFile.sendMessage(operator, LanguageFileField.ELEVATED_OPERATOR_OVERRIDE_VICTIM_MESSAGE, + b -> b.add(LanguageFileTag.player, newOperator.getName())); + operator = newOperator; + return true; + } + return false; + } + + private void removeCurrentOperator(){ + if(operator == null) return; + + operator.getBukkitPlayer().closeInventory(); + operator.clearOperating(); + operator = null; + } + + @Override + public MinMaxWaitingTimer getWaitingTimer() { + return waitingTimer; + } + + @Override + public void onVehicleArrive(Vehicle vehicle, StationHandle stationHandle) { + waitingTimer.reset(); + } + + @Override + public void onVehicleDepart(Vehicle vehicle, StationHandle stationHandle) { + waitingTimer.reset(); + } + + @Override + public Player getOperator() { + return operator; + } + + @Override + public boolean allowsAction(ControlAction action, Player player) { + return player.equals(operator); + } + + @Override + public void setTriggerContext(TriggerContext triggerContext) { + this.triggerContext = triggerContext; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/controlmode/ControlMode.java b/src/main/java/com/jverbruggen/jrides/control/controlmode/ControlMode.java new file mode 100644 index 00000000..e746f192 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/controlmode/ControlMode.java @@ -0,0 +1,21 @@ +package com.jverbruggen.jrides.control.controlmode; + +import com.jverbruggen.jrides.control.ControlAction; +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.properties.MinMaxWaitingTimer; +import com.jverbruggen.jrides.models.ride.StationHandle; +import com.jverbruggen.jrides.models.ride.coaster.train.Vehicle; + +public interface ControlMode { + void tick(); + + void onVehicleArrive(Vehicle vehicle, StationHandle stationHandle); + void onVehicleDepart(Vehicle vehicle, StationHandle stationHandle); + boolean setOperator(Player player); + boolean allowsAction(ControlAction action, Player player); + + MinMaxWaitingTimer getWaitingTimer(); + Player getOperator(); + void setTriggerContext(TriggerContext triggerContext); +} diff --git a/src/main/java/com/jverbruggen/jrides/control/controlmode/SemiAutomaticMode.java b/src/main/java/com/jverbruggen/jrides/control/controlmode/SemiAutomaticMode.java new file mode 100644 index 00000000..811b90a8 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/controlmode/SemiAutomaticMode.java @@ -0,0 +1,44 @@ +package com.jverbruggen.jrides.control.controlmode; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.control.DispatchLockCollection; +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.language.LanguageFileTag; +import com.jverbruggen.jrides.models.properties.MinMaxWaitingTimer; +import com.jverbruggen.jrides.models.ride.StationHandle; +import com.jverbruggen.jrides.models.ride.coaster.train.Vehicle; + +public class SemiAutomaticMode extends BaseControlMode implements ControlMode { + + public SemiAutomaticMode(RideHandle rideHandle, TriggerContext triggerContext, MinMaxWaitingTimer waitingTimer) { + super(rideHandle, triggerContext, waitingTimer); + + waitingTimer.setReachedTimeFunction(waitingTimer::reachedMinimum); + } + + @Override + public void tick() { + super.tick(); + + MinMaxWaitingTimer waitingTimer = getWaitingTimer(); + + StationHandle stationHandle = triggerContext.getParentStation(); + if(stationHandle == null) return; + + Vehicle stationaryVehicle = stationHandle.getStationaryVehicle(); + if(stationaryVehicle == null) return; + + waitingTimer.sendGenericWaitingNotification(stationaryVehicle.getPassengers()); + + + if(getOperator() != null){ + if(waitingTimer.reachedMaximum()){ + languageFile.sendMessage(getOperator(), + LanguageFileField.NOTIFICATION_OPERATOR_IDLE_TOO_LONG, + b->b.add(LanguageFileTag.rideDisplayName, rideHandle.getRide().getDisplayName())); + getOperator().getOperating().setOperator(null); + } + } + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/controlmode/VoidMode.java b/src/main/java/com/jverbruggen/jrides/control/controlmode/VoidMode.java new file mode 100644 index 00000000..52c49a0d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/controlmode/VoidMode.java @@ -0,0 +1,51 @@ +package com.jverbruggen.jrides.control.controlmode; + +import com.jverbruggen.jrides.control.ControlAction; +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.properties.MinMaxWaitingTimer; +import com.jverbruggen.jrides.models.ride.StationHandle; +import com.jverbruggen.jrides.models.ride.coaster.train.Vehicle; + +public class VoidMode implements ControlMode { + + @Override + public void tick() { + + } + + @Override + public void onVehicleArrive(Vehicle vehicle, StationHandle stationHandle) { + + } + + @Override + public void onVehicleDepart(Vehicle vehicle, StationHandle stationHandle) { + + } + + @Override + public boolean setOperator(Player player) { + return false; + } + + @Override + public boolean allowsAction(ControlAction action, Player player) { + return false; + } + + @Override + public MinMaxWaitingTimer getWaitingTimer() { + return null; + } + + @Override + public Player getOperator() { + return null; + } + + @Override + public void setTriggerContext(TriggerContext triggerContext) { + + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/controlmode/advanced/ProxyControlMode.java b/src/main/java/com/jverbruggen/jrides/control/controlmode/advanced/ProxyControlMode.java new file mode 100644 index 00000000..5a795c35 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/controlmode/advanced/ProxyControlMode.java @@ -0,0 +1,50 @@ +//package com.jverbruggen.jrides.control.controlmode.advanced; +// +//import com.jverbruggen.jrides.animator.RideHandle; +//import com.jverbruggen.jrides.control.controlmode.BaseControlMode; +//import com.jverbruggen.jrides.control.controlmode.ControlMode; +//import com.jverbruggen.jrides.models.properties.MinMaxWaitingTimer; +//import com.jverbruggen.jrides.models.ride.StationHandle; +//import com.jverbruggen.jrides.models.ride.coaster.train.Train; +// +//import java.util.List; +// +//public class ProxyControlMode extends BaseControlMode implements ControlMode { +//// private List targets; +//// private List stationHandles; +//// +//// public ProxyControlMode(RideHandle rideHandle, MinMaxWaitingTimer waitingTimer, List stationHandles) { +//// super(rideHandle, null, +//// waitingTimer, +//// null, +//// true); +//// +//// this.stationHandles = stationHandles; +//// } +//// +//// @Override +//// protected void incrementWaitingTimer() { +//// stationHandles.forEach(s -> s.getWaitingTimer().increment(tickInterval)); +//// } +//// +//// @Override +//// public StationHandle getStationHandle() { +//// throw new RuntimeException("Cannot get station handle in proxy control mode"); +//// } +//// +//// @Override +//// public void onVehicleArrive(Train train, StationHandle stationHandle) { +//// targets.stream().filter(t -> t.getStationHandle() == stationHandle) +//// .findFirst() +//// .orElseThrow(() -> new RuntimeException("Station handle not found on vehicle arrive!")) +//// .onVehicleArrive(train, stationHandle); +//// } +//// +//// @Override +//// public void onVehicleDepart(Train train, StationHandle stationHandle) { +//// targets.stream().filter(t -> t.getStationHandle() == stationHandle) +//// .findFirst() +//// .orElseThrow(() -> new RuntimeException("Station handle not found on vehicle depart!")) +//// .onVehicleDepart(train, stationHandle); +//// } +//} diff --git a/src/main/java/com/jverbruggen/jrides/control/controlmode/factory/ControlModeFactory.java b/src/main/java/com/jverbruggen/jrides/control/controlmode/factory/ControlModeFactory.java new file mode 100644 index 00000000..91502236 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/controlmode/factory/ControlModeFactory.java @@ -0,0 +1,65 @@ +package com.jverbruggen.jrides.control.controlmode.factory; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.control.controlmode.*; +import com.jverbruggen.jrides.models.properties.MinMaxWaitingTimer; +import com.jverbruggen.jrides.models.ride.StationHandle; + +import java.util.List; + +public class ControlModeFactory { + public ControlMode getForWithOperator(RideHandle rideHandle){ + if(rideHandle == null) return null; + + List stationHandles = rideHandle.getStationHandles(); + int size = stationHandles.size(); + if(size == 0) + return null; + else if(size == 1) + return getSingleForWithOperator(rideHandle, stationHandles.get(0)); + else{ + throw new RuntimeException("No support for multiple stations yet for control mode ( with operator )"); + } + } + + public ControlMode getForWithoutOperator(RideHandle rideHandle){ + if(rideHandle == null) return null; + + List stationHandles = rideHandle.getStationHandles(); + int size = stationHandles.size(); + if(size == 0) + return new VoidMode(); + else if(size == 1) + return createSimpleAutomaticMode(rideHandle, stationHandles.get(0)); + else{ + // For dispatching 1 station at a time + return getAlternateForWithoutOperator(rideHandle, stationHandles); + } + } + + private ControlMode getSingleForWithOperator(RideHandle rideHandle, StationHandle stationHandle){ + if(stationHandle == null) return null; + MinMaxWaitingTimer waitingTimer = stationHandle.getWaitingTimer(); + + return new SemiAutomaticMode( + rideHandle, + stationHandle.getTriggerContext(), + waitingTimer); + } + + private ControlMode createSimpleAutomaticMode(RideHandle rideHandle, StationHandle stationHandle){ + if(stationHandle == null) return null; + MinMaxWaitingTimer waitingTimer = stationHandle.getWaitingTimer(); + + return new AutomaticMode( + rideHandle, + stationHandle.getTriggerContext(), + waitingTimer); + } + + private ControlMode getAlternateForWithoutOperator(RideHandle rideHandle, List stationHandles){ + ControlMode automaticMode = createSimpleAutomaticMode(rideHandle, stationHandles.get(0)); + + return new AutomaticAlternateMode(automaticMode, stationHandles); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/operatingmode/OperationalMode.java b/src/main/java/com/jverbruggen/jrides/control/operatingmode/OperationalMode.java new file mode 100644 index 00000000..a812d29c --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/operatingmode/OperationalMode.java @@ -0,0 +1,4 @@ +package com.jverbruggen.jrides.control.operatingmode; + +public class OperationalMode { +} diff --git a/src/main/java/com/jverbruggen/jrides/control/operatingmode/ShuntingMode.java b/src/main/java/com/jverbruggen/jrides/control/operatingmode/ShuntingMode.java new file mode 100644 index 00000000..0731efee --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/operatingmode/ShuntingMode.java @@ -0,0 +1,4 @@ +package com.jverbruggen.jrides.control.operatingmode; + +public class ShuntingMode { +} diff --git a/src/main/java/com/jverbruggen/jrides/control/trigger/DispatchTrigger.java b/src/main/java/com/jverbruggen/jrides/control/trigger/DispatchTrigger.java new file mode 100644 index 00000000..4ea664e2 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/trigger/DispatchTrigger.java @@ -0,0 +1,9 @@ +package com.jverbruggen.jrides.control.trigger; + +import com.jverbruggen.jrides.control.DispatchLockCollection; + +public interface DispatchTrigger extends Trigger { + void reset(); + boolean isActive(); + DispatchLockCollection getDispatchLockCollection(); +} diff --git a/src/main/java/com/jverbruggen/jrides/control/trigger/GateTrigger.java b/src/main/java/com/jverbruggen/jrides/control/trigger/GateTrigger.java new file mode 100644 index 00000000..8ca76851 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/trigger/GateTrigger.java @@ -0,0 +1,90 @@ +package com.jverbruggen.jrides.control.trigger; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.common.Result; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.control.DispatchLock; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; +import com.jverbruggen.jrides.models.ride.CoasterStationHandle; +import com.jverbruggen.jrides.models.ride.StationHandle; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.coaster.train.Vehicle; + +public class GateTrigger implements StationTrigger{ + private StationHandle stationHandle; + private final DispatchLock gatesLock; + private final LanguageFile languageFile; + + public GateTrigger(DispatchLock gatesLock) { + this.stationHandle = null; + this.gatesLock = gatesLock; + this.languageFile = JRidesPlugin.getLanguageFile(); + } + + @Override + public void setStationHandle(StationHandle stationHandle) { + this.stationHandle = stationHandle; + } + + @Override + public DispatchLock getLock() { + return gatesLock; + } + + @Override + public boolean execute(MessageAgent messageAgent) { + Result canExecuteResult = canExecute(messageAgent); + if(!canExecuteResult.ok()){ + canExecuteResult.sendMessageTo(messageAgent); + return false; + } + + boolean set = setGatesState(!stationHandle.areEntryGatesClosed()); + if(!set){ + languageFile.sendMessage(messageAgent, LanguageFileField.NOTIFICATION_RIDE_NO_TRAIN_PRESENT); + return false; + } + + return true; + } + + @Override + public Result canExecute(MessageAgent messageAgent) { + if(messageAgent != null && !messageAgent.hasPermission(Permissions.CABIN_OPERATE)){ + return Result.isNotOk(languageFile.get(LanguageFileField.ERROR_OPERATING_NO_PERMISSION)); + } + + if(stationHandle == null){ + JRidesPlugin.getLogger().severe("No station handle set for gate trigger"); + return Result.isNotOk(); + } + + Vehicle stationaryTrain = stationHandle.getStationaryVehicle(); + if(stationaryTrain == null) { + return Result.isNotOk(); + } + + return Result.isOk(); + } + + public boolean setGatesState(boolean closed){ + if(gatesLock.isUnlocked() == closed) return false; + + Vehicle stationaryTrain = stationHandle.getStationaryVehicle(); + if(stationaryTrain == null) { + return false; + } + + if(closed){ + stationHandle.closeEntryGates(); + gatesLock.setLocked(false); + }else{ + gatesLock.setLocked(true); + stationHandle.openEntryGates(); + } + + return true; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/trigger/MultiDispatchTrigger.java b/src/main/java/com/jverbruggen/jrides/control/trigger/MultiDispatchTrigger.java new file mode 100644 index 00000000..f99201a6 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/trigger/MultiDispatchTrigger.java @@ -0,0 +1,77 @@ +package com.jverbruggen.jrides.control.trigger; + +import com.jverbruggen.jrides.common.Result; +import com.jverbruggen.jrides.control.DispatchLockCollection; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; + +import java.util.List; + +public class MultiDispatchTrigger implements DispatchTrigger { + private final List dispatchTriggerList; + private final DispatchLockCollection dispatchLockCollection; + private final LanguageFile languageFile; + + public MultiDispatchTrigger(List dispatchTriggerList, DispatchLockCollection dispatchLockCollection) { + this.dispatchTriggerList = dispatchTriggerList; + this.dispatchLockCollection = dispatchLockCollection; + this.languageFile = ServiceProvider.getSingleton(LanguageFile.class); + } + + @Override + public boolean execute(MessageAgent messageAgent){ + Result canExecuteResult = canExecute(messageAgent); + if(!canExecuteResult.ok()){ + languageFile.sendMessage(messageAgent, languageFile.get(LanguageFileField.NOTIFICATION_RIDE_DISPATCH_PROBLEMS)); + canExecuteResult.sendMessageTo(messageAgent); + return false; + } + + for(DispatchTrigger dispatchTrigger : dispatchTriggerList){ + dispatchTrigger.execute(messageAgent); + } + + return true; + } + + @Override + public Result canExecute(MessageAgent messageAgent) { + Result result = null; + + for(DispatchTrigger dispatchTrigger : dispatchTriggerList){ + Result canExecuteResult = dispatchTrigger.canExecute(messageAgent); + + if(!canExecuteResult.ok()){ + if(result == null){ + result = canExecuteResult; + }else{ + result.concat(canExecuteResult); + } + } + } + + if(result == null) + result = Result.isOk(); + + return result; + } + + @Override + public void reset(){ + for(DispatchTrigger dispatchTrigger : dispatchTriggerList){ + dispatchTrigger.reset(); + } + } + + @Override + public boolean isActive(){ + return dispatchTriggerList.stream().anyMatch(DispatchTrigger::isActive); + } + + @Override + public DispatchLockCollection getDispatchLockCollection() { + return dispatchLockCollection; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/trigger/RestraintTrigger.java b/src/main/java/com/jverbruggen/jrides/control/trigger/RestraintTrigger.java new file mode 100644 index 00000000..a295de0b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/trigger/RestraintTrigger.java @@ -0,0 +1,85 @@ +package com.jverbruggen.jrides.control.trigger; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.common.Result; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.control.DispatchLock; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; +import com.jverbruggen.jrides.models.ride.CoasterStationHandle; +import com.jverbruggen.jrides.models.ride.StationHandle; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.coaster.train.Vehicle; + +public class RestraintTrigger implements StationTrigger { + private StationHandle stationHandle; + private final DispatchLock restraintLock; + private final LanguageFile languageFile; + + public RestraintTrigger(DispatchLock restraintLock) { + this.stationHandle = null; + this.restraintLock = restraintLock; + this.languageFile = JRidesPlugin.getLanguageFile(); + } + + @Override + public void setStationHandle(StationHandle stationHandle) { + this.stationHandle = stationHandle; + } + + @Override + public DispatchLock getLock() { + return restraintLock; + } + + @Override + public boolean execute(MessageAgent messageAgent) { + Result canExecuteResult = canExecute(messageAgent); + if(!canExecuteResult.ok()){ + canExecuteResult.sendMessageTo(messageAgent); + return false; + } + + Vehicle stationaryTrain = stationHandle.getStationaryVehicle(); + if(!setRestraintsState(!stationaryTrain.getRestraintState())) { + languageFile.sendMessage(messageAgent, LanguageFileField.NOTIFICATION_RIDE_NO_TRAIN_PRESENT); + return false; + } + + return true; + } + + @Override + public Result canExecute(MessageAgent messageAgent) { + if(messageAgent != null && !messageAgent.hasPermission(Permissions.CABIN_OPERATE)){ + return Result.isNotOk(languageFile.get(LanguageFileField.ERROR_OPERATING_NO_PERMISSION)); + } + + if(stationHandle == null){ + JRidesPlugin.getLogger().severe("No station handle set for restraint trigger"); + return Result.isNotOk(); + } + + Vehicle stationaryTrain = stationHandle.getStationaryVehicle(); + + if(stationaryTrain == null) { + return Result.isNotOk(languageFile.get(LanguageFileField.NOTIFICATION_RIDE_NO_TRAIN_PRESENT)); + } + + return Result.isOk(); + } + + public boolean setRestraintsState(boolean closed){ + if(restraintLock.isUnlocked() == closed) return false; + + Vehicle stationaryTrain = stationHandle.getStationaryVehicle(); + if(stationaryTrain == null) { + return false; + } + + stationaryTrain.setRestraintForAll(closed); + restraintLock.setLocked(!closed); + return true; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/trigger/SimpleDispatchTrigger.java b/src/main/java/com/jverbruggen/jrides/control/trigger/SimpleDispatchTrigger.java new file mode 100644 index 00000000..253715ea --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/trigger/SimpleDispatchTrigger.java @@ -0,0 +1,65 @@ +package com.jverbruggen.jrides.control.trigger; + +import com.jverbruggen.jrides.common.Result; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.control.DispatchLockCollection; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; + +public class SimpleDispatchTrigger implements DispatchTrigger { + private boolean active; + private final DispatchLockCollection dispatchLockCollection; + private final LanguageFile languageFile; + + public SimpleDispatchTrigger(DispatchLockCollection dispatchLockCollection) { + this.active = false; + this.dispatchLockCollection = dispatchLockCollection; + this.languageFile = ServiceProvider.getSingleton(LanguageFile.class); + } + + @Override + public boolean execute(MessageAgent messageAgent){ + Result canExecuteResult = canExecute(messageAgent); + if(!canExecuteResult.ok()){ + languageFile.sendMessage(messageAgent, languageFile.get(LanguageFileField.NOTIFICATION_RIDE_DISPATCH_PROBLEMS)); + canExecuteResult.sendMessageTo(messageAgent); + return false; + } + + active = true; + return true; + } + + @Override + public Result canExecute(MessageAgent messageAgent) { + if(!dispatchLockCollection.allUnlocked()){ + if(messageAgent != null){ + return Result.isNotOk(dispatchLockCollection.getProblems(Integer.MAX_VALUE, messageAgent.hasPermission(Permissions.ELEVATED_DISPATCH_PROBLEMS_DEBUG))); + }else{ + return Result.isNotOk(); + } + } + if(messageAgent != null && !messageAgent.hasPermission(Permissions.CABIN_OPERATE)){ + return Result.isNotOk(languageFile.get(LanguageFileField.ERROR_OPERATING_NO_PERMISSION)); + } + + return Result.isOk(); + } + + @Override + public void reset(){ + active = false; + } + + @Override + public boolean isActive(){ + return active; + } + + @Override + public DispatchLockCollection getDispatchLockCollection() { + return dispatchLockCollection; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/trigger/StationTrigger.java b/src/main/java/com/jverbruggen/jrides/control/trigger/StationTrigger.java new file mode 100644 index 00000000..8f42c57d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/trigger/StationTrigger.java @@ -0,0 +1,10 @@ +package com.jverbruggen.jrides.control.trigger; + +import com.jverbruggen.jrides.control.DispatchLock; +import com.jverbruggen.jrides.models.ride.CoasterStationHandle; +import com.jverbruggen.jrides.models.ride.StationHandle; + +public interface StationTrigger extends Trigger { + void setStationHandle(StationHandle stationHandle); + DispatchLock getLock(); +} diff --git a/src/main/java/com/jverbruggen/jrides/control/trigger/Trigger.java b/src/main/java/com/jverbruggen/jrides/control/trigger/Trigger.java new file mode 100644 index 00000000..ccf6a181 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/trigger/Trigger.java @@ -0,0 +1,10 @@ +package com.jverbruggen.jrides.control.trigger; + +import com.jverbruggen.jrides.common.Result; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; + +public interface Trigger { + boolean execute(MessageAgent messageAgent); + + Result canExecute(MessageAgent messageAgent); +} diff --git a/src/main/java/com/jverbruggen/jrides/control/trigger/TriggerContext.java b/src/main/java/com/jverbruggen/jrides/control/trigger/TriggerContext.java new file mode 100644 index 00000000..f062fe18 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/trigger/TriggerContext.java @@ -0,0 +1,63 @@ +package com.jverbruggen.jrides.control.trigger; + +import com.jverbruggen.jrides.control.DispatchLock; +import com.jverbruggen.jrides.control.DispatchLockCollection; +import com.jverbruggen.jrides.models.ride.StationHandle; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public class TriggerContext { + private final DispatchLockCollection dispatchLockCollection; + private final DispatchLock vehiclePresentLock; + private final SimpleDispatchTrigger dispatchTrigger; + private final GateTrigger gateTrigger; + private final RestraintTrigger restraintTrigger; + private @Nullable StationHandle parentStation; + + public TriggerContext(DispatchLockCollection dispatchLockCollection, DispatchLock vehiclePresentLock, SimpleDispatchTrigger dispatchTrigger, GateTrigger gateTrigger, RestraintTrigger restraintTrigger) { + this.dispatchLockCollection = dispatchLockCollection; + this.vehiclePresentLock = vehiclePresentLock; + this.dispatchTrigger = dispatchTrigger; + this.gateTrigger = gateTrigger; + this.restraintTrigger = restraintTrigger; + this.parentStation = null; + } + + public SimpleDispatchTrigger getDispatchTrigger() { + return dispatchTrigger; + } + + public DispatchLock getVehiclePresentLock() { + return vehiclePresentLock; + } + + public GateTrigger getGateTrigger() { + return gateTrigger; + } + + public RestraintTrigger getRestraintTrigger() { + return restraintTrigger; + } + + public DispatchLockCollection getDispatchLockCollection() { + return dispatchLockCollection; + } + + @Nullable + public StationHandle getParentStation() { + return parentStation; + } + + public void setParentStation(@Nonnull StationHandle parentStation) { + this.parentStation = parentStation; + } + + @Override + public String toString() { + return "TriggerContext{" + + "vehiclePresentLock=" + vehiclePresentLock + + ", parentStation=" + parentStation + + '}'; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/RideControlMenuFactory.java b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/RideControlMenuFactory.java new file mode 100644 index 00000000..678b1188 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/RideControlMenuFactory.java @@ -0,0 +1,189 @@ +package com.jverbruggen.jrides.control.uiinterface.menu; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.common.MenuSessionManager; +import com.jverbruggen.jrides.config.coaster.objects.ControllerConfig; +import com.jverbruggen.jrides.control.DispatchLockCollection; +import com.jverbruggen.jrides.control.controller.DualRideController; +import com.jverbruggen.jrides.control.controller.RideController; +import com.jverbruggen.jrides.control.trigger.*; +import com.jverbruggen.jrides.control.uiinterface.menu.button.factory.RideControlButtonFactory; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.language.LanguageFileTag; +import com.jverbruggen.jrides.models.menu.Menu; +import com.jverbruggen.jrides.models.menu.MenuButton; +import com.jverbruggen.jrides.models.menu.SimpleMenu; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; + +import java.util.*; + +public class RideControlMenuFactory { + private final MenuSessionManager menuSessionManager; + private final LanguageFile languageFile; + private final RideControlButtonFactory rideControlButtonFactory; + + private final Map adminRideControlMenus; + + public RideControlMenuFactory() { + this.menuSessionManager = ServiceProvider.getSingleton(MenuSessionManager.class); + this.languageFile = ServiceProvider.getSingleton(LanguageFile.class); + this.rideControlButtonFactory = ServiceProvider.getSingleton(RideControlButtonFactory.class); + + this.adminRideControlMenus = new HashMap<>(); + } + + public Menu getRideControlMenu(RideController rideController, ControllerConfig controllerConfig){ + String type = controllerConfig != null ? controllerConfig.getType() : null; + + if(!rideController.supportsMenu()) { + return null; + }else if(type == null || type.equalsIgnoreCase(ControllerConfig.CONTROLLER_DEFAULT)){ + return getSimpleControlMenu(rideController); + }else if(type.equalsIgnoreCase(ControllerConfig.CONTROLLER_ALTERNATE)){ + return getAlternateControlMenu((DualRideController) rideController); + }else if(type.equalsIgnoreCase(ControllerConfig.CONTROLLER_SIMULTANEOUS)){ + return getSimultaneousMenu((DualRideController) rideController); + }else + throw new RuntimeException("Cannot create ride control menu of type " + type); + } + + public SimpleMenu getSimpleControlMenu(RideController rideController){ + if(rideController == null || !rideController.isActive()) + return null; + + DispatchLockCollection dispatchLockCollection = rideController.getTriggerContext().getDispatchLockCollection(); + + SimpleDispatchTrigger dispatchTrigger = rideController.getTriggerContext().getDispatchTrigger(); + StationTrigger gateTrigger = rideController.getTriggerContext().getGateTrigger(); + StationTrigger restraintTrigger = rideController.getTriggerContext().getRestraintTrigger(); + + MenuButton claimOperatingButton = rideControlButtonFactory.createClaimRideButton(rideController, 4); + MenuButton dispatchButton = rideControlButtonFactory.createDispatchButton(dispatchTrigger, 10); + MenuButton problemList = rideControlButtonFactory.createProblemList(dispatchLockCollection, 11); + MenuButton gateButton = rideControlButtonFactory.createGateButton(gateTrigger, 15); + MenuButton restraintButton = rideControlButtonFactory.createRestraintButton(restraintTrigger, 16); + + SimpleMenu rideControlMenu = new SimpleMenu(3, getRideControlMenuTitle(rideController)); + rideControlMenu.addButton(claimOperatingButton); + rideControlMenu.addButton(dispatchButton); + rideControlMenu.addButton(problemList); + rideControlMenu.addButton(gateButton); + rideControlMenu.addButton(restraintButton); + + return rideControlMenu; + } + + public Menu getAlternateControlMenu(DualRideController rideController){ + if(!rideController.isActive()) + return null; + + TriggerContext leftStationTriggerContext = rideController.getLeftStationTriggerContext(); + SimpleDispatchTrigger leftDispatchTrigger = leftStationTriggerContext.getDispatchTrigger(); + StationTrigger leftGateTrigger = leftStationTriggerContext.getGateTrigger(); + StationTrigger leftRestraintTrigger = leftStationTriggerContext.getRestraintTrigger(); + TriggerContext rightStationTriggerContext = rideController.getRightStationTriggerContext(); + SimpleDispatchTrigger rightDispatchTrigger = rightStationTriggerContext.getDispatchTrigger(); + StationTrigger rightGateTrigger = rightStationTriggerContext.getGateTrigger(); + StationTrigger rightRestraintTrigger = rightStationTriggerContext.getRestraintTrigger(); + + MenuButton claimOperatingButton = rideControlButtonFactory.createClaimRideButton(rideController, 4); + MenuButton leftProblemList = rideControlButtonFactory.createProblemList(leftStationTriggerContext.getDispatchLockCollection(), 18); + MenuButton leftDispatchButton = rideControlButtonFactory.createDispatchButton(leftDispatchTrigger, 9); + MenuButton leftGateButton = rideControlButtonFactory.createGateButton(leftGateTrigger, 10); + MenuButton leftRestraintButton = rideControlButtonFactory.createRestraintButton(leftRestraintTrigger, 11); + MenuButton rightProblemList = rideControlButtonFactory.createProblemList(rightStationTriggerContext.getDispatchLockCollection(), 24); + MenuButton rightDispatchButton = rideControlButtonFactory.createDispatchButton(rightDispatchTrigger, 15); + MenuButton rightGateButton = rideControlButtonFactory.createGateButton(rightGateTrigger, 16); + MenuButton rightRestraintButton = rideControlButtonFactory.createRestraintButton(rightRestraintTrigger, 17); + + Menu rideControlMenu = new SimpleMenu(3, getRideControlMenuTitle(rideController)); + rideControlMenu.addButton(claimOperatingButton); + rideControlMenu.addButton(leftProblemList); + rideControlMenu.addButton(leftDispatchButton); + rideControlMenu.addButton(leftGateButton); + rideControlMenu.addButton(leftRestraintButton); + rideControlMenu.addButton(rightProblemList); + rideControlMenu.addButton(rightDispatchButton); + rideControlMenu.addButton(rightGateButton); + rideControlMenu.addButton(rightRestraintButton); + + return rideControlMenu; + } + + public Menu getSimultaneousMenu(DualRideController rideController){ + if(!rideController.isActive()) + return null; + + TriggerContext leftStationTriggerContext = rideController.getLeftStationTriggerContext(); + SimpleDispatchTrigger leftDispatchTrigger = leftStationTriggerContext.getDispatchTrigger(); + StationTrigger leftGateTrigger = leftStationTriggerContext.getGateTrigger(); + StationTrigger leftRestraintTrigger = leftStationTriggerContext.getRestraintTrigger(); + TriggerContext rightStationTriggerContext = rideController.getRightStationTriggerContext(); + SimpleDispatchTrigger rightDispatchTrigger = rightStationTriggerContext.getDispatchTrigger(); + StationTrigger rightGateTrigger = rightStationTriggerContext.getGateTrigger(); + StationTrigger rightRestraintTrigger = rightStationTriggerContext.getRestraintTrigger(); + + List dispatchTriggers = List.of(leftDispatchTrigger, rightDispatchTrigger); + DispatchLockCollection leftDispatchLockCollection = leftDispatchTrigger.getDispatchLockCollection(); + DispatchLockCollection rightDispatchLockCollection = rightDispatchTrigger.getDispatchLockCollection(); + DispatchLockCollection hybridDispatchLockCollection = DispatchLockCollection.makeHybrid( + "Main locks", + leftDispatchLockCollection, + rightDispatchLockCollection); + leftDispatchLockCollection.addEventListener(hybridDispatchLockCollection.toStatusListener()); + rightDispatchLockCollection.addEventListener(hybridDispatchLockCollection.toStatusListener()); + MultiDispatchTrigger simultaneousDispatchTrigger = new MultiDispatchTrigger(dispatchTriggers, hybridDispatchLockCollection); + + MenuButton claimOperatingButton = rideControlButtonFactory.createClaimRideButton(rideController, 4); + MenuButton dispatchButton = rideControlButtonFactory.createDispatchButton(simultaneousDispatchTrigger, 9); + MenuButton leftProblemList = rideControlButtonFactory.createProblemList(leftStationTriggerContext.getDispatchLockCollection(), 20); + MenuButton leftGateButton = rideControlButtonFactory.createGateButton(leftGateTrigger, 11); + MenuButton leftRestraintButton = rideControlButtonFactory.createRestraintButton(leftRestraintTrigger, 12); + MenuButton rightProblemList = rideControlButtonFactory.createProblemList(rightStationTriggerContext.getDispatchLockCollection(), 23); + MenuButton rightGateButton = rideControlButtonFactory.createGateButton(rightGateTrigger, 14); + MenuButton rightRestraintButton = rideControlButtonFactory.createRestraintButton(rightRestraintTrigger, 15); + + Menu rideControlMenu = new SimpleMenu(3, getRideControlMenuTitle(rideController)); + rideControlMenu.addButton(claimOperatingButton); + rideControlMenu.addButton(dispatchButton); + rideControlMenu.addButton(leftProblemList); + rideControlMenu.addButton(leftGateButton); + rideControlMenu.addButton(leftRestraintButton); + rideControlMenu.addButton(rightProblemList); + rideControlMenu.addButton(rightGateButton); + rideControlMenu.addButton(rightRestraintButton); + + return rideControlMenu; + } + + public Menu getAdminMenu(RideController rideController){ + if(rideController == null || !rideController.isActive()) + return null; + if(adminRideControlMenus.containsKey(rideController)) + return adminRideControlMenus.get(rideController); + + RideHandle rideHandle = rideController.getRideHandle(); + + MenuButton openRideButton = rideControlButtonFactory.createStateOpenRideButton(rideHandle, 3); + MenuButton closeRideButton = rideControlButtonFactory.createStateCloseRideButton(rideHandle, 5); + + Menu adminRideControlMenu = new SimpleMenu(1, getAdminRideControlMenuTitle(rideController)); + adminRideControlMenu.addButton(openRideButton); + adminRideControlMenu.addButton(closeRideButton); + + adminRideControlMenus.put(rideController, adminRideControlMenu); + + return adminRideControlMenu; + } + + private String getRideControlMenuTitle(RideController rideController){ + return languageFile.get(LanguageFileField.MENU_RIDE_CONTROL_TITLE, + b -> b.add(LanguageFileTag.rideDisplayName, rideController.getRide().getDisplayName())); + } + + private String getAdminRideControlMenuTitle(RideController rideController){ + return languageFile.get(LanguageFileField.MENU_ADMIN_RIDE_CONTROL_TITLE, + b -> b.add(LanguageFileTag.rideDisplayName, rideController.getRide().getDisplayName())); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/BaseRideControlButton.java b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/BaseRideControlButton.java new file mode 100644 index 00000000..5ab93a2f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/BaseRideControlButton.java @@ -0,0 +1,25 @@ +package com.jverbruggen.jrides.control.uiinterface.menu.button; + +import com.jverbruggen.jrides.models.menu.ButtonVisual; +import com.jverbruggen.jrides.models.menu.MenuButton; +import org.bukkit.Sound; + +public abstract class BaseRideControlButton implements MenuButton { + protected void setButtonVisual(ButtonVisual visual){ + visual.clearUpdate(); + + if(visual.needsFullItemStackReload()){ + setItemStack(visual.toItemStack()); + return; + } + + changeMaterial(visual.getButtonMaterial()); + changeDisplayName(visual.getButtonDisplayNameColor() + visual.getValue()); + changeLore(visual.getLore()); + } + + @Override + public Sound getPressedSound() { + return Sound.UI_BUTTON_CLICK; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/LockResembledControlButton.java b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/LockResembledControlButton.java new file mode 100644 index 00000000..5151693b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/LockResembledControlButton.java @@ -0,0 +1,116 @@ +package com.jverbruggen.jrides.control.uiinterface.menu.button; + +import com.jverbruggen.jrides.control.DispatchLock; +import com.jverbruggen.jrides.models.menu.*; +import com.jverbruggen.jrides.models.menu.ButtonVisual; +import com.jverbruggen.jrides.control.uiinterface.menu.button.controller.ButtonUpdateController; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.UUID; + +public class LockResembledControlButton extends BaseRideControlButton implements MenuButton { + private MenuButton parentButton; + private boolean buttonOkState; + private final ButtonVisual buttonBlockedVisual; + private final ButtonVisual buttonOkVisual; + private final DispatchLock lock; + + public LockResembledControlButton(ButtonVisual buttonBlockedVisual, ButtonVisual buttonOkVisual, int slot, DispatchLock lock, MenuButtonAction action) { + this.buttonBlockedVisual = buttonBlockedVisual; + this.buttonOkVisual = buttonOkVisual; + this.lock = lock; + this.buttonOkState = isLockOk(); + + this.parentButton = new SimpleMenuButton( + getActiveVisual(), slot, action); + + this.lock.addEventListener(this::onLockEvent); + ServiceProvider.getSingleton(ButtonUpdateController.class).addButton(this, 10); + } + + private void onLockEvent(DispatchLock lock){ + updateState(); + } + + private boolean isLockOk(){ + return lock.isUnlocked(); + } + + public void sendUpdate(){ + parentButton.sendUpdate(); + } + + public void changeDisplayName(String displayName){ + parentButton.changeDisplayName(displayName); + } + + public void changeMaterial(Material material){ + parentButton.changeMaterial(material); + } + + public void changeTitleColor(ChatColor color){ + parentButton.changeTitleColor(color); + } + + public void changeLore(List lore){ + parentButton.changeLore(lore); + } + + public ItemStack getItemStack(){ + return parentButton.getItemStack(); + } + + public void setItemStack(ItemStack itemStack) { + parentButton.setItemStack(itemStack); + } + + public void setVisible(boolean visible){ + parentButton.setVisible(visible); + } + + public void setParentMenu(Menu parentMenu) { + parentButton.setParentMenu(parentMenu); + } + + public Menu getParentMenu() { + return parentButton.getParentMenu(); + } + + public UUID getUuid() { + return parentButton.getUuid(); + } + + public int getSlot() { + return parentButton.getSlot(); + } + + public void press(Player player){ + parentButton.press(player); + updateState(); + } + + private void updateState(){ + buttonOkState = isLockOk(); + setButtonVisual(getActiveVisual()); + sendUpdate(); + } + + @Override + public ButtonVisual getActiveVisual() { + if(buttonOkState){ + return buttonOkVisual; + }else return buttonBlockedVisual; + } + + @Override + public void updateVisual() { + setButtonVisual(getActiveVisual()); + sendUpdate(); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/action/RunnableButtonAction.java b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/action/RunnableButtonAction.java new file mode 100644 index 00000000..12acb01b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/action/RunnableButtonAction.java @@ -0,0 +1,20 @@ +package com.jverbruggen.jrides.control.uiinterface.menu.button.action; + +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.menu.MenuButton; +import com.jverbruggen.jrides.models.menu.MenuButtonAction; + +import java.util.function.Consumer; + +public class RunnableButtonAction implements MenuButtonAction { + private Consumer consumerFunction; + + public RunnableButtonAction(Consumer consumerFunction) { + this.consumerFunction = consumerFunction; + } + + @Override + public void run(Player player, MenuButton button) { + consumerFunction.accept(player); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/action/RunnableButtonWithContextAction.java b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/action/RunnableButtonWithContextAction.java new file mode 100644 index 00000000..f2623f4c --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/action/RunnableButtonWithContextAction.java @@ -0,0 +1,20 @@ +package com.jverbruggen.jrides.control.uiinterface.menu.button.action; + +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.menu.MenuButton; +import com.jverbruggen.jrides.models.menu.MenuButtonAction; + +import java.util.function.BiConsumer; + +public class RunnableButtonWithContextAction implements MenuButtonAction { + private BiConsumer consumerFunction; + + public RunnableButtonWithContextAction(BiConsumer consumerFunction) { + this.consumerFunction = consumerFunction; + } + + @Override + public void run(Player player, MenuButton button) { + consumerFunction.accept(player, button); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/common/BlinkingButtonVisual.java b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/common/BlinkingButtonVisual.java new file mode 100644 index 00000000..c0d120e6 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/common/BlinkingButtonVisual.java @@ -0,0 +1,75 @@ +package com.jverbruggen.jrides.control.uiinterface.menu.button.common; + +import com.jverbruggen.jrides.models.menu.ButtonVisual; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +public class BlinkingButtonVisual implements ButtonVisual { + private final StaticButtonVisual blinkLowVisual; + private final StaticButtonVisual blinkHighVisual; + private boolean blinkHigh; + private StaticButtonVisual activeVisual; + private boolean hasUpdate; + + public BlinkingButtonVisual(StaticButtonVisual blinkLowVisual, StaticButtonVisual blinkHighVisual) { + this.blinkLowVisual = blinkLowVisual; + this.blinkHighVisual = blinkHighVisual; + this.activeVisual = blinkLowVisual; + this.blinkHigh = false; + this.hasUpdate = false; + } + + private ButtonVisual updateButtonVisual(){ + this.blinkHigh = !this.blinkHigh; + this.hasUpdate = true; + + this.activeVisual = blinkHigh ? blinkHighVisual : blinkLowVisual; + return activeVisual; + } + + public ChatColor getButtonDisplayNameColor() { + return activeVisual.getButtonDisplayNameColor(); + } + + public Material getButtonMaterial() { + return activeVisual.getButtonMaterial(); + } + + public ItemStack toItemStack(){ + return activeVisual.toItemStack(); + } + + @Override + public boolean update() { + updateButtonVisual(); + return true; + } + + @Override + public boolean hasUpdate() { + return hasUpdate; + } + + @Override + public List getLore() { + return activeVisual.getLore(); + } + + @Override + public void clearUpdate() { + hasUpdate = false; + } + + @Override + public boolean needsFullItemStackReload() { + return false; + } + + @Override + public String getValue() { + return activeVisual.getValue(); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/common/CabinOccupationVisual.java b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/common/CabinOccupationVisual.java new file mode 100644 index 00000000..8d551e8b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/common/CabinOccupationVisual.java @@ -0,0 +1,98 @@ +package com.jverbruggen.jrides.control.uiinterface.menu.button.common; + +import com.jverbruggen.jrides.control.controller.RideController; +import com.jverbruggen.jrides.items.ItemStackFactory; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.menu.ButtonVisual; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +public class CabinOccupationVisual implements ButtonVisual { + private final RideController rideController; + private final ButtonVisual noOccupationVisual; + private Player operator; + private boolean hasUpdate; + private final String operatedString; + + public CabinOccupationVisual(RideController rideController, ButtonVisual noOccupationVisual, String operatedString) { + this.rideController = rideController; + this.noOccupationVisual = noOccupationVisual; + this.operatedString = operatedString; + this.operator = null; + this.hasUpdate = false; + } + + private boolean checkForUpdate(){ + Player actualOperator = rideController.getOperator(); + if(actualOperator != null && !actualOperator.equals(operator)){ + this.operator = actualOperator; + this.hasUpdate = true; + }else if(actualOperator == null){ + this.operator = null; + this.hasUpdate = true; + } + return hasUpdate; + } + + private boolean isBeingOperated(){ + checkForUpdate(); + Player actualOperator = rideController.getOperator(); + + return actualOperator != null; + } + + @Override + public ChatColor getButtonDisplayNameColor() { + if(operator == null) return noOccupationVisual.getButtonDisplayNameColor(); + throw new RuntimeException("Should be updated through toItemStack"); + } + + @Override + public Material getButtonMaterial() { + if(operator == null) return noOccupationVisual.getButtonMaterial(); + throw new RuntimeException("Should be updated through toItemStack"); + } + + @Override + public String getValue() { + if(operator == null) return getButtonDisplayNameColor() + noOccupationVisual.getValue(); + throw new RuntimeException("Should be updated through toItemStack"); + } + + @Override + public ItemStack toItemStack() { + if(!isBeingOperated()){ + return ItemStackFactory.getRideControlButtonStack(getButtonMaterial(), getValue()); + } + + return ItemStackFactory.getPlayerHead(operator, ChatColor.GOLD + operatedString); + } + + @Override + public boolean update() { + return false; + } + + @Override + public boolean hasUpdate() { + return checkForUpdate(); + } + + @Override + public List getLore() { + return List.of(); + } + + @Override + public void clearUpdate() { + hasUpdate = false; + } + + @Override + public boolean needsFullItemStackReload() { + return true; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/common/StatefulButtonVisual.java b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/common/StatefulButtonVisual.java new file mode 100644 index 00000000..27ace391 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/common/StatefulButtonVisual.java @@ -0,0 +1,89 @@ +package com.jverbruggen.jrides.control.uiinterface.menu.button.common; + +import com.jverbruggen.jrides.models.menu.ButtonVisual; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import javax.annotation.Nonnull; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +public class StatefulButtonVisual implements ButtonVisual { + + private final Supplier state; + private final Map options; + private final T _default; + private @Nonnull ButtonVisual current; + + private boolean hasUpdate; + + public StatefulButtonVisual(Supplier state, Map options, T _default) { + this.state = state; + this.options = options; + this._default = _default; + this.current = options.get(_default); + this.hasUpdate = false; + } + + public void updateCurrent(){ + ButtonVisual newCurrent = options.get(state.get()); + if(newCurrent == null) + throw new RuntimeException("StatefulButtonVisual wanted to update to a visual option that did not exist"); + + if(current != newCurrent) + hasUpdate = true; + + current = newCurrent; + } + + + @Override + public ChatColor getButtonDisplayNameColor() { + return current.getButtonDisplayNameColor(); + } + + @Override + public Material getButtonMaterial() { + return current.getButtonMaterial(); + } + + @Override + public String getValue() { + return current.getValue(); + } + + @Override + public ItemStack toItemStack() { + return current.toItemStack(); + } + + @Override + public boolean update() { + updateCurrent(); + current.update(); + return true; + } + + @Override + public boolean hasUpdate() { + return current.hasUpdate() || hasUpdate; + } + + @Override + public List getLore() { + return current.getLore(); + } + + @Override + public void clearUpdate() { + current.clearUpdate(); + hasUpdate = false; + } + + @Override + public boolean needsFullItemStackReload() { + return current.needsFullItemStackReload(); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/common/StaticButtonVisual.java b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/common/StaticButtonVisual.java new file mode 100644 index 00000000..d5a95bed --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/common/StaticButtonVisual.java @@ -0,0 +1,95 @@ +package com.jverbruggen.jrides.control.uiinterface.menu.button.common; + +import com.jverbruggen.jrides.models.menu.ButtonVisual; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemFlag; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.List; + +public class StaticButtonVisual implements ButtonVisual { + private final ChatColor buttonDisplayNameColor; + private final String value; + private final List lore; + private final ItemStack itemStack; + + public StaticButtonVisual(Material material, ChatColor buttonDisplayNameColor, String value) { + this.itemStack = new ItemStack(material); + this.buttonDisplayNameColor = buttonDisplayNameColor; + this.value = value; + this.lore = List.of(); + } + + public StaticButtonVisual(ItemStack itemStack, ChatColor buttonDisplayNameColor, String value) { + this.itemStack = itemStack; + this.buttonDisplayNameColor = buttonDisplayNameColor; + this.value = value; + this.lore = List.of(); + } + + public StaticButtonVisual(Material material, ChatColor buttonDisplayNameColor, String value, List lore) { + this.itemStack = new ItemStack(material); + this.buttonDisplayNameColor = buttonDisplayNameColor; + this.value = value; + this.lore = lore; + } + + public StaticButtonVisual(ItemStack itemStack, ChatColor buttonDisplayNameColor, String value, List lore) { + this.itemStack = itemStack; + this.buttonDisplayNameColor = buttonDisplayNameColor; + this.value = value; + this.lore = lore; + } + + public ChatColor getButtonDisplayNameColor() { + return buttonDisplayNameColor; + } + + public Material getButtonMaterial() { + return itemStack.getType(); + } + + @Override + public String getValue() { + return value; + } + + public ItemStack toItemStack(){ + ItemStack itemStack = this.itemStack.clone(); + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.setDisplayName(buttonDisplayNameColor + value); + if(lore.size() != 0) itemMeta.setLore(lore); + itemMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); + itemMeta.addItemFlags(ItemFlag.HIDE_UNBREAKABLE); + itemStack.setItemMeta(itemMeta); + + return itemStack; + } + + @Override + public boolean update() { + return false; + } + + @Override + public boolean hasUpdate() { + return false; + } + + @Override + public List getLore() { + return lore; + } + + @Override + public void clearUpdate() { + + } + + @Override + public boolean needsFullItemStackReload() { + return true; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/controller/ButtonUpdateController.java b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/controller/ButtonUpdateController.java new file mode 100644 index 00000000..d87d37c5 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/controller/ButtonUpdateController.java @@ -0,0 +1,48 @@ +package com.jverbruggen.jrides.control.uiinterface.menu.button.controller; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.models.menu.MenuButton; +import org.bukkit.Bukkit; + +import java.util.ArrayList; +import java.util.List; + +public class ButtonUpdateController { + private List buttonUpdateStateList; + + public ButtonUpdateController() { + this.buttonUpdateStateList = new ArrayList<>(); + Bukkit.getScheduler().runTaskTimer(JRidesPlugin.getBukkitPlugin(), this::tick, 1L, 1L).getTaskId(); + } + + public void addButton(MenuButton button, int interval){ + buttonUpdateStateList.add(new ButtonUpdateState(button, interval)); + } + + private void tick() { + buttonUpdateStateList.forEach(ButtonUpdateState::tick); + } +} + +class ButtonUpdateState{ + private final MenuButton button; + private final int interval; + private int intervalState; + + ButtonUpdateState(MenuButton button, int interval) { + this.button = button; + this.interval = interval; + this.intervalState = 0; + } + + void tick(){ + intervalState++; + if(intervalState < interval) return; + intervalState = 0; + + boolean updated = button.getActiveVisual().update(); + if(updated){ + button.updateVisual(); + } + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/event/ButtonClickEventListener.java b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/event/ButtonClickEventListener.java new file mode 100644 index 00000000..6fe170f6 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/event/ButtonClickEventListener.java @@ -0,0 +1,95 @@ +package com.jverbruggen.jrides.control.uiinterface.menu.button.event; + +import com.jverbruggen.jrides.common.MenuSessionManager; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.menu.Menu; +import com.jverbruggen.jrides.models.menu.MenuButton; +import com.jverbruggen.jrides.models.menu.SimpleMenuButton; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.player.PlayerManager; +import de.tr7zw.nbtapi.NBTItem; +import org.bukkit.Material; +import org.bukkit.entity.HumanEntity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.*; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.util.UUID; + +public class ButtonClickEventListener implements Listener { + private final MenuSessionManager menuSessionManager; + private final PlayerManager playerManager; + + public ButtonClickEventListener() { + this.menuSessionManager = ServiceProvider.getSingleton(MenuSessionManager.class); + this.playerManager = ServiceProvider.getSingleton(PlayerManager.class); + } + + @EventHandler + public void onClick(InventoryClickEvent event){ + Inventory clickedInventory = event.getClickedInventory(); + if(event.getView().getTopInventory() != clickedInventory) return; + + Player player = playerManager.getPlayer((org.bukkit.entity.Player) event.getWhoClicked()); + if(!menuSessionManager.hasOpenMenu(player)) return; + + Menu menu = menuSessionManager.getOpenMenu(player); + if(menu.getSessions().get(player) != clickedInventory) return; + + if(event.getAction() != InventoryAction.PICKUP_ALL){ + event.setCancelled(true); + return; + } + + ItemStack item = event.getCurrentItem(); + if(item == null || item.getType() == Material.AIR) return; + + NBTItem nbtItem = new NBTItem(item); + if(!nbtItem.hasTag(SimpleMenuButton.BUTTON_UUID_KEY)) return; + + String buttonUUIDString = nbtItem.getString(SimpleMenuButton.BUTTON_UUID_KEY); + UUID buttonUUID = UUID.fromString(buttonUUIDString); + + MenuButton button = menu.getButton(buttonUUID); + button.press(player); + + event.setCancelled(true); + } + + @EventHandler + public void onItemMoveTowardsMenuClick(InventoryClickEvent event){ + onItemTowardsMenu(event, event.getClickedInventory()); + } + + @EventHandler(priority = EventPriority.LOW) + public void onItemMoveTowardsMenuDrag(InventoryDragEvent event){ + onItemTowardsMenu(event, event.getInventory()); + } + + private void onItemTowardsMenu(InventoryInteractEvent event, Inventory destination){ + HumanEntity whoClicked = event.getWhoClicked(); + if(!(whoClicked instanceof org.bukkit.entity.Player)) + return; + + Player player = playerManager.getPlayer((org.bukkit.entity.Player) whoClicked); + if(event.getView().getTopInventory() != destination) + return; + + if(!menuSessionManager.hasOpenMenu(player)) return; + + Menu menu = menuSessionManager.getOpenMenu(player); + if(menu.getSessions().get(player) != destination) return; + + event.setCancelled(true); + player.getBukkitPlayer().updateInventory(); + } + + @EventHandler + public void onClose(InventoryCloseEvent event){ + Player player = playerManager.getPlayer((org.bukkit.entity.Player) event.getPlayer()); + menuSessionManager.removeOpenMenu(player); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/factory/RideControlButtonFactory.java b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/factory/RideControlButtonFactory.java new file mode 100644 index 00000000..6577ec93 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/button/factory/RideControlButtonFactory.java @@ -0,0 +1,129 @@ +package com.jverbruggen.jrides.control.uiinterface.menu.button.factory; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.control.DispatchLockCollection; +import com.jverbruggen.jrides.control.controller.RideController; +import com.jverbruggen.jrides.control.trigger.DispatchTrigger; +import com.jverbruggen.jrides.control.trigger.SimpleDispatchTrigger; +import com.jverbruggen.jrides.control.trigger.StationTrigger; +import com.jverbruggen.jrides.control.uiinterface.menu.button.LockResembledControlButton; +import com.jverbruggen.jrides.control.uiinterface.menu.button.action.RunnableButtonAction; +import com.jverbruggen.jrides.control.uiinterface.menu.button.action.RunnableButtonWithContextAction; +import com.jverbruggen.jrides.control.uiinterface.menu.button.common.BlinkingButtonVisual; +import com.jverbruggen.jrides.control.uiinterface.menu.button.common.CabinOccupationVisual; +import com.jverbruggen.jrides.control.uiinterface.menu.button.common.StaticButtonVisual; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.language.LanguageFileTag; +import com.jverbruggen.jrides.models.menu.MenuButton; +import com.jverbruggen.jrides.models.menu.SimpleMenuButton; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.ChatColor; +import org.bukkit.Material; + +import java.util.List; + +public class RideControlButtonFactory { + private final LanguageFile languageFile; + + public RideControlButtonFactory(){ + this.languageFile = ServiceProvider.getSingleton(LanguageFile.class); + } + + public MenuButton createClaimRideButton(RideController rideController, int slot){ + String rideDisplayName = rideController.getRide().getDisplayName(); + return new SimpleMenuButton( + new CabinOccupationVisual(rideController, + new StaticButtonVisual(Material.BLACK_CONCRETE_POWDER, + ChatColor.GOLD, + languageFile.get(LanguageFileField.BUTTON_CLAIM_CABIN, b -> b.add(LanguageFileTag.rideDisplayName, rideDisplayName))), + languageFile.get(LanguageFileField.BUTTON_CABIN_CLAIMED, b -> b.add(LanguageFileTag.rideDisplayName, rideDisplayName))), + slot, new RunnableButtonWithContextAction((p, b) -> { + if(!p.hasPermission(Permissions.CABIN_OPERATE)) return; + if(p.equals(rideController.getOperator())){ + p.setOperating(null); + }else{ + p.setOperating(rideController); + } + })); + } + + public MenuButton createRestraintButton(StationTrigger restraintTrigger, int slot){ + return new LockResembledControlButton( + new BlinkingButtonVisual( + new StaticButtonVisual(Material.WHITE_CONCRETE, + ChatColor.WHITE, languageFile.get(LanguageFileField.BUTTON_RESTRAINTS_OPEN_STATE)), + new StaticButtonVisual(Material.LIGHT_GRAY_CONCRETE, + ChatColor.GRAY, languageFile.get(LanguageFileField.BUTTON_RESTRAINTS_OPEN_STATE)) + ), + new StaticButtonVisual(Material.WHITE_CONCRETE, + ChatColor.WHITE, languageFile.get(LanguageFileField.BUTTON_RESTRAINTS_CLOSED_STATE)), + slot, restraintTrigger.getLock(), new RunnableButtonAction(restraintTrigger::execute)); + } + + public MenuButton createGateButton(StationTrigger gateTrigger, int slot){ + return new LockResembledControlButton( + new BlinkingButtonVisual( + new StaticButtonVisual(Material.WHITE_CONCRETE, + ChatColor.WHITE, languageFile.get(LanguageFileField.BUTTON_GATES_OPEN_STATE)), + new StaticButtonVisual(Material.LIGHT_GRAY_CONCRETE, + ChatColor.GRAY, languageFile.get(LanguageFileField.BUTTON_GATES_OPEN_STATE)) + ), + new StaticButtonVisual(Material.WHITE_CONCRETE, + ChatColor.WHITE, languageFile.get(LanguageFileField.BUTTON_GATES_CLOSED_STATE)), + slot, gateTrigger.getLock(), new RunnableButtonAction(gateTrigger::execute)); + } + + public MenuButton createProblemList(DispatchLockCollection dispatchLockCollection, int slot){ + MenuButton problemList = new SimpleMenuButton( + new StaticButtonVisual(Material.ITEM_FRAME, + ChatColor.RED, languageFile.get(LanguageFileField.BUTTON_PROBLEMS_STATE)), + slot, null); + problemList.changeLore(dispatchLockCollection.getProblems(1, false)); + + dispatchLockCollection.addEventListener(lock -> { + List problems = dispatchLockCollection.getProblems(1, false); + if(problems.size() == 0){ + problemList.setVisible(false); + }else{ + problemList.setVisible(true); + problemList.changeLore(problems); + } + + problemList.sendUpdate(); + }); + + return problemList; + } + + public MenuButton createDispatchButton(DispatchTrigger dispatchTrigger, int slot){ + return new LockResembledControlButton( + new StaticButtonVisual(Material.GREEN_CONCRETE, ChatColor.DARK_GREEN, + languageFile.get(LanguageFileField.BUTTON_DISPATCH_STATE), + List.of(ChatColor.GRAY + languageFile.get(LanguageFileField.BUTTON_DISPATCH_PROBLEM_STATE))), + new BlinkingButtonVisual( + new StaticButtonVisual(Material.LIME_CONCRETE, + ChatColor.GREEN, languageFile.get(LanguageFileField.BUTTON_DISPATCH_STATE)), + new StaticButtonVisual(Material.GREEN_CONCRETE, + ChatColor.DARK_GREEN, languageFile.get(LanguageFileField.BUTTON_DISPATCH_STATE)) + ), + slot, dispatchTrigger.getDispatchLockCollection(), new RunnableButtonAction(dispatchTrigger::execute)); + } + + public MenuButton createStateOpenRideButton(RideHandle rideHandle, int slot){ + return new SimpleMenuButton( + new StaticButtonVisual(Material.GREEN_CONCRETE, ChatColor.DARK_GREEN, "Open ride"), + slot, + new RunnableButtonAction(rideHandle::open) + ); + } + + public MenuButton createStateCloseRideButton(RideHandle rideHandle, int slot){ + return new SimpleMenuButton( + new StaticButtonVisual(Material.RED_CONCRETE, ChatColor.RED, "Close ride"), + slot, + new RunnableButtonAction(rideHandle::close) + ); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/open/SignMenuListener.java b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/open/SignMenuListener.java new file mode 100644 index 00000000..5c9e344c --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/control/uiinterface/menu/open/SignMenuListener.java @@ -0,0 +1,92 @@ +package com.jverbruggen.jrides.control.uiinterface.menu.open; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.common.MenuSessionManager; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.language.FeedbackType; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.menu.Menu; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.player.PlayerManager; +import com.jverbruggen.jrides.state.ride.RideManager; +import org.bukkit.ChatColor; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.block.Sign; +import org.bukkit.block.data.BlockData; +import org.bukkit.block.data.type.WallSign; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.Inventory; + +public class SignMenuListener implements Listener { + private final String secondLineTriggerText; + private final LanguageFile languageFile; + private final RideManager rideManager; + private final PlayerManager playerManager; + private final MenuSessionManager menuSessionManager; + + public SignMenuListener(String secondLineTriggerText) { + this.secondLineTriggerText = secondLineTriggerText; + this.languageFile = ServiceProvider.getSingleton(LanguageFile.class); + this.rideManager = ServiceProvider.getSingleton(RideManager.class); + this.playerManager = ServiceProvider.getSingleton(PlayerManager.class); + this.menuSessionManager = ServiceProvider.getSingleton(MenuSessionManager.class); + } + + /** + * Sign format: + *
--- + *
+ *
[< ride_identifier >] + *
Control panel + *
+ *
--- + * @param event + */ + @EventHandler + public void onSignClick(PlayerInteractEvent event){ + if(!event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) return; + + + Block block = event.getClickedBlock(); + BlockData blockData = block.getBlockData(); + if(!(blockData instanceof WallSign)) return; + + Sign sign = (Sign) block.getState(); + String lineText = ChatColor.stripColor(sign.getLine(2)); + if(!lineText.equalsIgnoreCase(secondLineTriggerText)) return; + + String identifierRaw = sign.getLine(1); + String identifier = identifierRaw + .replace("[", "") + .replace("]", ""); + + Player player = playerManager.getPlayer(event.getPlayer()); + if(!player.hasPermission(Permissions.CABIN_OPERATE)){ + JRidesPlugin.getLanguageFile().sendMessage(player, LanguageFileField.ERROR_OPERATING_NO_PERMISSION); + return; + } + + + RideHandle rideHandle = rideManager.getRideHandle(identifier); + if(rideHandle == null) return; + + Menu rideControlMenu = rideHandle.getRideControlMenu(); + if(rideControlMenu == null){ + languageFile.sendMessage(player, LanguageFileField.ERROR_RIDE_CONTROL_MENU_NOT_FOUND, FeedbackType.CONFLICT); + return; + } + + Inventory inventory = rideControlMenu.getInventoryFor(player); + + menuSessionManager.addOpenMenu(player, rideControlMenu, inventory); + player.getBukkitPlayer().openInventory(inventory); + player.playSound(Sound.UI_BUTTON_CLICK); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/EffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/EffectTrigger.java new file mode 100644 index 00000000..8794cde1 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/EffectTrigger.java @@ -0,0 +1,9 @@ +package com.jverbruggen.jrides.effect; + +import com.jverbruggen.jrides.effect.handle.EffectTriggerHandle; +import com.jverbruggen.jrides.models.properties.frame.Frame; + +public interface EffectTrigger { + boolean finishedPlaying(); + EffectTriggerHandle createHandle(Frame frame, boolean reversed); +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/EffectTriggerCollection.java b/src/main/java/com/jverbruggen/jrides/effect/EffectTriggerCollection.java new file mode 100644 index 00000000..cc2e7409 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/EffectTriggerCollection.java @@ -0,0 +1,26 @@ +package com.jverbruggen.jrides.effect; + +import com.jverbruggen.jrides.effect.handle.EffectTriggerHandle; + +import java.util.LinkedList; +import java.util.List; + +public class EffectTriggerCollection { + private final LinkedList effectTriggers; + + public EffectTriggerCollection(LinkedList effectTriggers) { + this.effectTriggers = effectTriggers; + } + + public int size(){ + return effectTriggers.size(); + } + + public T first(){ + return effectTriggers.get(0); + } + + public LinkedList getLinkedList(){ + return effectTriggers; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/EffectTriggerFactory.java b/src/main/java/com/jverbruggen/jrides/effect/EffectTriggerFactory.java new file mode 100644 index 00000000..2e813972 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/EffectTriggerFactory.java @@ -0,0 +1,127 @@ +package com.jverbruggen.jrides.effect; + +import com.jverbruggen.jrides.config.ConfigManager; +import com.jverbruggen.jrides.config.trigger.TriggerConfig; +import com.jverbruggen.jrides.effect.handle.EffectTriggerHandle; +import com.jverbruggen.jrides.effect.handle.cart.CartEffectTriggerHandle; +import com.jverbruggen.jrides.effect.handle.train.TrainEffectTriggerHandle; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.frame.factory.FrameFactory; +import com.jverbruggen.jrides.models.ride.RideType; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import net.minecraft.util.Tuple; +import org.bukkit.Bukkit; +import org.bukkit.configuration.ConfigurationSection; + +import java.util.*; +import java.util.function.BiConsumer; +import java.util.stream.Collectors; + +public class EffectTriggerFactory { + private final ConfigManager configManager; + private final Map effectTriggerMap; + private final FrameFactory frameFactory; + + public EffectTriggerFactory() { + this.configManager = ServiceProvider.getSingleton(ConfigManager.class); + this.effectTriggerMap = new HashMap<>(); + this.frameFactory = ServiceProvider.getSingleton(FrameFactory.class); + } + + private T getEffectTrigger(Class clazz, String rideIdentifier, String effectName, boolean reversed, Frame frame, TriggerConfig triggerConfig){ + if(triggerConfig == null) + throw new RuntimeException("Trigger config was null for effect '" + effectName + "' in ride '" + rideIdentifier + "'"); + + EffectTrigger effectTrigger; + String mapKey = rideIdentifier + ":" + effectName; + if(!effectTriggerMap.containsKey(mapKey)){ + effectTrigger = triggerConfig.createTrigger(); + + effectTriggerMap.put(mapKey, effectTrigger); + }else{ + effectTrigger = effectTriggerMap.get(mapKey); + } + + EffectTriggerHandle effectTriggerHandle = effectTrigger.createHandle(frame, reversed); + + if(!clazz.isInstance(effectTriggerHandle)) + return null; + + return clazz.cast(effectTriggerHandle); + } + + public TrainEffectTriggerHandle getTrainEffectTrigger(String rideIdentifier, String effectName, boolean reversed, Frame frame, TriggerConfig triggerConfig){ + return getEffectTrigger(TrainEffectTriggerHandle.class, rideIdentifier, effectName, reversed, frame, triggerConfig); + } + + public CartEffectTriggerHandle getCartEffectTrigger(String rideIdentifier, String effectName, boolean reversed, Frame frame, TriggerConfig triggerConfig){ + return getEffectTrigger(CartEffectTriggerHandle.class, rideIdentifier, effectName, reversed, frame, triggerConfig); + } + + public List getFramelessEffectTriggers(RideType rideType, String rideIdentifier, List effectNames){ + if(effectNames == null) return null; + return effectNames + .stream() + .map(effectNameRaw -> { + String[] effectNameRawComponents = effectNameRaw.split(":"); + String effectName = effectNameRawComponents[0]; + boolean reversed = false; + if(effectNameRawComponents.length == 2){ + reversed = effectNameRawComponents[1].equalsIgnoreCase("reversed"); + } + return getTrainEffectTrigger(rideIdentifier, effectName, reversed, null, configManager.getTriggerConfig(rideType, rideIdentifier, effectName)); + }) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + + private EffectTriggerCollection getEffectTriggerCollectionGeneric(Class clazz, String rideIdentifier, Track track, BiConsumer setNextFunction){ + ConfigurationSection allEffectsConfigurationSection = configManager.getAllEffectsConfigSection(rideIdentifier, "default"); + if(allEffectsConfigurationSection == null) + return null; + + boolean goneRound = false; + int lastFrameIndex = Integer.MIN_VALUE; + List> effects = new ArrayList<>(); + Set effectIdentifiers = allEffectsConfigurationSection.getKeys(false); + for(String effectIdentifier : effectIdentifiers){ + ConfigurationSection effectConfigurationSection = allEffectsConfigurationSection.getConfigurationSection(effectIdentifier); + int frameIndex = effectConfigurationSection.getInt("frame"); + if(lastFrameIndex > frameIndex){ + if(goneRound) + throw new RuntimeException("Every effect trigger frame needs to be after the frame of the effect before (except for once going round)"); + + goneRound = true; + } + + effects.add(new Tuple<>(frameFactory.getStaticFrame(frameIndex, track), effectIdentifier)); + + lastFrameIndex = frameIndex; + } + + T previous = null; + LinkedList effectTriggers = new LinkedList<>(); + for(Tuple effect : effects){ + Frame frame = effect.getA(); + String effectName = effect.getB(); + + T effectTrigger = getEffectTrigger(clazz, rideIdentifier, effectName, false, frame, configManager.getTriggerConfig(RideType.COASTER, rideIdentifier, effectName)); + if(effectTrigger == null) continue; + if(previous != null) setNextFunction.accept(previous, effectTrigger); + effectTriggers.add(effectTrigger); + + previous = effectTrigger; + } + + return new EffectTriggerCollection<>(effectTriggers); + } + + public EffectTriggerCollection getTrainEffectTriggers(String rideIdentifier, Track track){ + return getEffectTriggerCollectionGeneric(TrainEffectTriggerHandle.class, rideIdentifier, track, TrainEffectTriggerHandle::setNext); + } + + public EffectTriggerCollection getCartEffectTriggers(String rideIdentifier, Track track){ + return getEffectTriggerCollectionGeneric(CartEffectTriggerHandle.class, rideIdentifier, track, CartEffectTriggerHandle::setNext); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/cart/BaseCartEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/cart/BaseCartEffectTrigger.java new file mode 100644 index 00000000..b006988b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/cart/BaseCartEffectTrigger.java @@ -0,0 +1,12 @@ +package com.jverbruggen.jrides.effect.cart; + +import com.jverbruggen.jrides.effect.handle.EffectTriggerHandle; +import com.jverbruggen.jrides.effect.handle.cart.DefaultCartEffectTriggerHandle; +import com.jverbruggen.jrides.models.properties.frame.Frame; + +public abstract class BaseCartEffectTrigger implements CartEffectTrigger { + @Override + public EffectTriggerHandle createHandle(Frame frame, boolean reversed) { + return new DefaultCartEffectTriggerHandle(frame, this); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/cart/CartEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/cart/CartEffectTrigger.java new file mode 100644 index 00000000..72aee966 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/cart/CartEffectTrigger.java @@ -0,0 +1,20 @@ +package com.jverbruggen.jrides.effect.cart; + +import com.jverbruggen.jrides.effect.EffectTrigger; +import com.jverbruggen.jrides.models.ride.coaster.train.CoasterCart; + +public interface CartEffectTrigger extends EffectTrigger { + /** + * + * @param cart + * @return true if can process more effects + */ + boolean execute(CoasterCart cart); + + /** + * + * @param cart + * @return true if can process more effects + */ + boolean executeReversed(CoasterCart cart); +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/cart/CartRestraintEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/cart/CartRestraintEffectTrigger.java new file mode 100644 index 00000000..a728bcf7 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/cart/CartRestraintEffectTrigger.java @@ -0,0 +1,28 @@ +package com.jverbruggen.jrides.effect.cart; + +import com.jverbruggen.jrides.models.ride.coaster.train.CoasterCart; +import org.bukkit.Bukkit; + +public class CartRestraintEffectTrigger extends BaseCartEffectTrigger { + public final boolean locked; + + public CartRestraintEffectTrigger(boolean locked) { + this.locked = locked; + } + + @Override + public boolean finishedPlaying() { + return true; + } + + @Override + public boolean execute(CoasterCart cart) { + cart.setRestraint(locked); + return true; + } + + @Override + public boolean executeReversed(CoasterCart cart) { + return execute(cart); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/cart/rotation/CartRotationEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/cart/rotation/CartRotationEffectTrigger.java new file mode 100644 index 00000000..99f819f3 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/cart/rotation/CartRotationEffectTrigger.java @@ -0,0 +1,33 @@ +package com.jverbruggen.jrides.effect.cart.rotation; + +import com.jverbruggen.jrides.effect.cart.BaseCartEffectTrigger; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.ride.coaster.train.CoasterCart; + +public class CartRotationEffectTrigger extends BaseCartEffectTrigger { + private final Vector3 rotation; + private final int animationTicks; + private int animationTickState; + + public CartRotationEffectTrigger(Vector3 rotation, int animationTicks) { + this.rotation = rotation; + this.animationTicks = animationTicks; + this.animationTickState = 0; + } + + @Override + public boolean execute(CoasterCart cart) { + cart.updateCustomOrientationOffset(rotation); + return true; + } + + @Override + public boolean executeReversed(CoasterCart cart) { + return execute(cart); + } + + @Override + public boolean finishedPlaying() { + return true; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/entity/EntityContinuousMovementEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/entity/EntityContinuousMovementEffectTrigger.java new file mode 100644 index 00000000..9ad86fcb --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/entity/EntityContinuousMovementEffectTrigger.java @@ -0,0 +1,87 @@ +package com.jverbruggen.jrides.effect.entity; + +import com.jverbruggen.jrides.effect.entity.common.DelayedEntityTask; +import com.jverbruggen.jrides.effect.train.BaseTrainEffectTrigger; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +public class EntityContinuousMovementEffectTrigger extends BaseTrainEffectTrigger implements EntityMovementTrigger { + private final VirtualEntity virtualEntity; + + private final DelayedEntityTask delayedEntityTask; + + private final Vector3 initialLocation; + private final Quaternion initialRotation; + private final boolean resetOnStart; + + private final Vector3 locationDelta; + private final Quaternion rotationDelta; + + public EntityContinuousMovementEffectTrigger(VirtualEntity virtualEntity, Vector3 initialLocation, Quaternion initialRotation, boolean resetOnStart, Vector3 locationDelta, Quaternion rotationDelta, int animationTimeTicks, int delayTicks) { + this.virtualEntity = virtualEntity; + this.locationDelta = locationDelta; + this.rotationDelta = rotationDelta; + + this.delayedEntityTask = new DelayedEntityTask(this::runTask, delayTicks, animationTimeTicks); + + this.initialLocation = initialLocation; + this.initialRotation = initialRotation; + this.resetOnStart = resetOnStart; + } + + public VirtualEntity getVirtualEntity() { + return virtualEntity; + } + + private void runTask(){ + addPosition(); + addRotation(); + } + + private void addRotation(){ + if(rotationDelta == null) return; + + Quaternion result = Quaternion.multiply(virtualEntity.getRotation(), rotationDelta); + virtualEntity.setRotation(result); + } + + private void addPosition(){ + if(locationDelta == null) return; + + virtualEntity.setLocation(Vector3.add(locationDelta, virtualEntity.getLocation())); + } + + @Override + public boolean execute(Train train) { + start(); + return true; + } + + @Override + public boolean executeReversed(Train train) { + return execute(train); + } + + protected void start(){ + if(delayedEntityTask.isBusy()) return; + + if(resetOnStart){ + virtualEntity.setLocation(initialLocation); + virtualEntity.setRotation(initialRotation); + } + + delayedEntityTask.start(); + } + + @Override + public boolean finishedPlaying() { + return delayedEntityTask.isFinished(); + } + + @Override + public void onFinish(Runnable runnable) { + delayedEntityTask.addOnFinishRunnable(runnable); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/entity/EntityFromToMovementEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/entity/EntityFromToMovementEffectTrigger.java new file mode 100644 index 00000000..18da342b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/entity/EntityFromToMovementEffectTrigger.java @@ -0,0 +1,88 @@ +package com.jverbruggen.jrides.effect.entity; + +import com.jverbruggen.jrides.effect.entity.common.DelayedEntityTask; +import com.jverbruggen.jrides.effect.train.BaseTrainEffectTrigger; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +public class EntityFromToMovementEffectTrigger extends BaseTrainEffectTrigger implements EntityMovementTrigger { + private final VirtualEntity virtualEntity; + + private final DelayedEntityTask delayedEntityTask; + + private final Vector3 locationFrom; + private final Vector3 locationTo; + private final Quaternion rotationFrom; + private final Quaternion rotationTo; + + private Vector3 targetLocation; + + public EntityFromToMovementEffectTrigger(VirtualEntity virtualEntity, Vector3 locationFrom, Vector3 locationTo, Quaternion rotationFrom, Quaternion rotationTo, int animationTimeTicks, int delayTicks) { + this.virtualEntity = virtualEntity; + + this.locationFrom = locationFrom; + this.locationTo = locationTo; + this.rotationFrom = rotationFrom; + this.rotationTo = rotationTo; + + this.targetLocation = null; + this.delayedEntityTask = new DelayedEntityTask(this::runTask, delayTicks, animationTimeTicks); + } + + public int getAnimationTimeTicks() { + return delayedEntityTask.getAnimationTicks(); + } + + private void runTask(){ + lerpPosition(); + lerpRotation(); + } + + private void lerpRotation(){ + if(rotationFrom == null || rotationTo == null) return; + + double lerpIncrement = 1d/(double)getAnimationTimeTicks(); + double theta = lerpIncrement * delayedEntityTask.getCurrentAnimationTick(); + virtualEntity.setRotation(Quaternion.lerp(rotationFrom, rotationTo, theta)); + } + + private void lerpPosition(){ + if(locationFrom == null || locationTo == null) return; + + Vector3 currentLocation = virtualEntity.getLocation(); + Vector3 delta = Vector3.subtract(targetLocation, currentLocation); + double multiplication = 1.0 / (getAnimationTimeTicks() - delayedEntityTask.getCurrentAnimationTick()); + Vector3 newLocation = Vector3.add(Vector3.multiply(delta, multiplication), currentLocation); + virtualEntity.setLocation(newLocation); + } + + @Override + public boolean execute(Train train) { + if(delayedEntityTask.isBusy()) return true; + + targetLocation = locationTo; + delayedEntityTask.start(); + return true; + } + + @Override + public boolean executeReversed(Train train) { + if(delayedEntityTask.isBusy()) return true; + + targetLocation = locationFrom; + delayedEntityTask.start(); + return true; + } + + @Override + public boolean finishedPlaying() { + return delayedEntityTask.isFinished(); + } + + @Override + public void onFinish(Runnable runnable) { + delayedEntityTask.addOnFinishRunnable(runnable); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/entity/EntityMovementTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/entity/EntityMovementTrigger.java new file mode 100644 index 00000000..16a6decf --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/entity/EntityMovementTrigger.java @@ -0,0 +1,7 @@ +package com.jverbruggen.jrides.effect.entity; + +import com.jverbruggen.jrides.effect.train.TrainEffectTrigger; + +public interface EntityMovementTrigger extends TrainEffectTrigger { + void onFinish(Runnable runnable); +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/entity/EntityProjectileEffect.java b/src/main/java/com/jverbruggen/jrides/effect/entity/EntityProjectileEffect.java new file mode 100644 index 00000000..e1f444cc --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/entity/EntityProjectileEffect.java @@ -0,0 +1,110 @@ +package com.jverbruggen.jrides.effect.entity; + +import com.jverbruggen.jrides.effect.entity.common.DelayedEntityTask; +import com.jverbruggen.jrides.effect.train.BaseTrainEffectTrigger; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +public class EntityProjectileEffect extends BaseTrainEffectTrigger implements EntityMovementTrigger{ + private final VirtualEntity virtualEntity; + private final DelayedEntityTask delayedEntityTask; + private final boolean resetOnStart; + + private final Vector3 initialPosition; + private final Quaternion initialRotation; + + private final Vector3 initialPositionalVelocity; + private final Quaternion initialRotationalVelocity; + + private final Vector3 positionalAcceleration; + private final Quaternion rotationalAcceleration; + + private final Vector3 currentPositionalVelocity; + private final Quaternion currentRotationalVelocity; + + public EntityProjectileEffect(VirtualEntity virtualEntity, boolean resetOnStart, Vector3 initialPosition, Quaternion initialRotation, + Vector3 initialPositionalVelocity, Quaternion initialRotationalVelocity, Vector3 positionalAcceleration, Quaternion rotationalAcceleration, + int animationTimeTicks, int delayTicks) { + this.virtualEntity = virtualEntity; + this.delayedEntityTask = new DelayedEntityTask(this::runTask, delayTicks, animationTimeTicks); + this.delayedEntityTask.addOnFinishRunnable(this::onFinishCallback); + this.resetOnStart = resetOnStart; + + this.initialPosition = initialPosition; + this.initialRotation = initialRotation; + + this.initialPositionalVelocity = initialPositionalVelocity; + this.initialRotationalVelocity = initialRotationalVelocity; + + this.positionalAcceleration = positionalAcceleration; + this.rotationalAcceleration = rotationalAcceleration; + + this.currentPositionalVelocity = initialPosition.clone(); + this.currentRotationalVelocity = initialRotation.clone(); + } + + private void runTask(){ + addPosition(); + addRotation(); + } + + private void addPosition(){ + if(positionalAcceleration == null) return; + + this.currentPositionalVelocity.x += this.positionalAcceleration.x; + this.currentPositionalVelocity.y += this.positionalAcceleration.y; + this.currentPositionalVelocity.z += this.positionalAcceleration.z; + + virtualEntity.setLocation(Vector3.add(currentPositionalVelocity, virtualEntity.getLocation())); + } + + private void addRotation(){ + if(rotationalAcceleration == null) return; + + this.currentRotationalVelocity.multiply(this.rotationalAcceleration); + + Quaternion result = Quaternion.multiply(virtualEntity.getRotation(), currentRotationalVelocity); + virtualEntity.setRotation(result); + } + + protected void start(){ + if(delayedEntityTask.isBusy()) return; + + if(resetOnStart){ + virtualEntity.setLocation(initialPosition); + virtualEntity.setRotation(initialRotation); + } + + resetVelocity(); + virtualEntity.setRendered(true); + + delayedEntityTask.start(); + } + + private void resetVelocity(){ + this.currentPositionalVelocity.setTo(this.initialPositionalVelocity); + this.currentRotationalVelocity.setTo(this.initialRotationalVelocity); + } + + private void onFinishCallback(){ + virtualEntity.setRendered(false); + } + + @Override + public boolean finishedPlaying() { + return delayedEntityTask.isFinished(); + } + + @Override + public void onFinish(Runnable runnable) { + delayedEntityTask.addOnFinishRunnable(runnable); + } + + @Override + public boolean execute(Train train) { + start(); + return true; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/entity/MultipleEffectExecutorTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/entity/MultipleEffectExecutorTrigger.java new file mode 100644 index 00000000..f6a225e8 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/entity/MultipleEffectExecutorTrigger.java @@ -0,0 +1,30 @@ +package com.jverbruggen.jrides.effect.entity; + +import com.jverbruggen.jrides.effect.train.BaseTrainEffectTrigger; +import com.jverbruggen.jrides.effect.train.TrainEffectTrigger; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +import java.util.List; + +public class MultipleEffectExecutorTrigger extends BaseTrainEffectTrigger { + private final List triggers; + + public MultipleEffectExecutorTrigger(List triggers) { + this.triggers = triggers; + } + + @Override + public boolean execute(Train train) { + return triggers.stream().allMatch(a -> a.execute(train)); + } + + @Override + public boolean executeReversed(Train train) { + return triggers.stream().allMatch(a -> a.executeReversed(train)); + } + + @Override + public boolean finishedPlaying() { + return triggers.stream().allMatch(TrainEffectTrigger::finishedPlaying); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/entity/ReplaceItemEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/entity/ReplaceItemEffectTrigger.java new file mode 100644 index 00000000..9a610337 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/entity/ReplaceItemEffectTrigger.java @@ -0,0 +1,41 @@ +package com.jverbruggen.jrides.effect.entity; + +import com.jverbruggen.jrides.effect.entity.common.DelayedEntityTask; +import com.jverbruggen.jrides.effect.train.BaseTrainEffectTrigger; +import com.jverbruggen.jrides.models.entity.TrainModelItem; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +public class ReplaceItemEffectTrigger extends BaseTrainEffectTrigger implements EntityMovementTrigger { + private final TrainModelItem trainModelItem; + private final VirtualEntity targetEntity; + + private final DelayedEntityTask delayedEntityTask; + + + public ReplaceItemEffectTrigger(TrainModelItem trainModelItem, VirtualEntity targetEntity, int delayTicks) { + this.trainModelItem = trainModelItem; + this.targetEntity = targetEntity; + this.delayedEntityTask = new DelayedEntityTask(this::runTask, delayTicks); + } + + private void runTask(){ + targetEntity.setModel(trainModelItem); + } + + @Override + public boolean finishedPlaying() { + return delayedEntityTask.isFinished(); + } + + @Override + public boolean execute(Train train) { + this.delayedEntityTask.start(); + return true; + } + + @Override + public void onFinish(Runnable runnable) { + delayedEntityTask.addOnFinishRunnable(runnable); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/entity/common/DelayedEntityTask.java b/src/main/java/com/jverbruggen/jrides/effect/entity/common/DelayedEntityTask.java new file mode 100644 index 00000000..1b7428e3 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/entity/common/DelayedEntityTask.java @@ -0,0 +1,105 @@ +package com.jverbruggen.jrides.effect.entity.common; + +import com.jverbruggen.jrides.JRidesPlugin; +import org.bukkit.Bukkit; + +import java.util.ArrayList; +import java.util.List; + +public class DelayedEntityTask { + private final Runnable runnable; + private final List onFinishRunnables; + private final int animationTicks; + private final int delayTicks; + private int bukkitTimerTracker; + private boolean started; + private boolean finished; + + private int animationTickState; + private int delayTickState; + + public DelayedEntityTask(Runnable runnable, int delayTicks, int animationTicks){ + this.runnable = runnable; + this.onFinishRunnables = new ArrayList<>(); + this.animationTicks = animationTicks; + this.delayTicks = delayTicks; + this.started = false; + this.finished = false; + this.bukkitTimerTracker = -1; + } + + public DelayedEntityTask(Runnable runnable, int delayTicks){ + this(runnable, delayTicks, 0); + } + + public boolean isFinished() { + return finished; + } + + public boolean isBusy(){ + return started; + } + + public void addOnFinishRunnable(Runnable onFinishRunnable) { + this.onFinishRunnables.add(onFinishRunnable); + } + + public int getAnimationTicks() { + return animationTicks; + } + + public int getCurrentAnimationTick(){ + return animationTickState; + } + + private void runTask(){ + if(delayTickState < delayTicks){ + delayTickState++; + return; + } + + if(animationTicks == 0){ + runOnceAndStop(); + return; + } + + runUntilAnimationDone(); + } + + private void runOnceAndStop(){ + runnable.run(); + stop(); + } + + private void runUntilAnimationDone(){ + if(animationTickState >= animationTicks){ + stop(); + return; + } + + runnable.run(); + + animationTickState++; + } + + public void start(){ + if(started) return; + this.started = true; + this.finished = false; + this.delayTickState = 0; + this.animationTickState = 0; + + this.bukkitTimerTracker = Bukkit.getScheduler().runTaskTimer(JRidesPlugin.getBukkitPlugin(), this::runTask, 1L, 1L).getTaskId(); + } + + private void stop(){ + if(bukkitTimerTracker == -1) return; + this.started = false; + this.finished = true; + if(!onFinishRunnables.isEmpty()) + onFinishRunnables.forEach(Runnable::run); + + Bukkit.getScheduler().cancelTask(bukkitTimerTracker); + bukkitTimerTracker = -1; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/external/CommandAsPlayerEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/external/CommandAsPlayerEffectTrigger.java new file mode 100644 index 00000000..f934a2b1 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/external/CommandAsPlayerEffectTrigger.java @@ -0,0 +1,31 @@ +package com.jverbruggen.jrides.effect.external; + +import com.jverbruggen.jrides.effect.train.BaseTrainEffectTrigger; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +public class CommandAsPlayerEffectTrigger extends BaseTrainEffectTrigger { + private final String command; + + public CommandAsPlayerEffectTrigger(String command) { + this.command = command; + } + + @Override + public boolean finishedPlaying() { + return true; + } + + @Override + public boolean execute(Train train) { + for(Player player : train.getPassengers()){ + player.getBukkitPlayer().performCommand(command); + } + return true; + } + + @Override + public boolean executeReversed(Train train) { + return execute(train); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/external/CommandEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/external/CommandEffectTrigger.java new file mode 100644 index 00000000..5cd36c3b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/external/CommandEffectTrigger.java @@ -0,0 +1,24 @@ +package com.jverbruggen.jrides.effect.external; + +import com.jverbruggen.jrides.effect.train.BaseTrainEffectTrigger; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import org.bukkit.Bukkit; + +public class CommandEffectTrigger extends BaseTrainEffectTrigger { + private final String command; + + public CommandEffectTrigger(String command) { + this.command = command; + } + + @Override + public boolean finishedPlaying() { + return true; + } + + @Override + public boolean execute(Train train) { + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command); + return true; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/external/CommandForPlayerEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/external/CommandForPlayerEffectTrigger.java new file mode 100644 index 00000000..7541612a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/external/CommandForPlayerEffectTrigger.java @@ -0,0 +1,29 @@ +package com.jverbruggen.jrides.effect.external; + +import com.jverbruggen.jrides.effect.train.BaseTrainEffectTrigger; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import org.bukkit.Bukkit; + +public class CommandForPlayerEffectTrigger extends BaseTrainEffectTrigger { + private final String command; + + public CommandForPlayerEffectTrigger(String command) { + this.command = command; + } + + @Override + public boolean finishedPlaying() { + return true; + } + + @Override + public boolean execute(Train train) { + for(Player player : train.getPassengers()){ + String replacedCommand = command.replaceAll("%PLAYER%", player.getName()); + Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), replacedCommand); + } + + return true; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/external/animation/AnimatedJavaEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/external/animation/AnimatedJavaEffectTrigger.java new file mode 100644 index 00000000..573f35b0 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/external/animation/AnimatedJavaEffectTrigger.java @@ -0,0 +1,41 @@ +package com.jverbruggen.jrides.effect.external.animation; + +import com.jverbruggen.jrides.animator.animatedjava.AnimatedJavaExecutor; +import com.jverbruggen.jrides.common.Sync; +import com.jverbruggen.jrides.effect.train.BaseTrainEffectTrigger; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +public class AnimatedJavaEffectTrigger extends BaseTrainEffectTrigger { + private final AnimatedJavaExecutor executor; + private final String animationName; + private final int despawnAfterTicks; + + public AnimatedJavaEffectTrigger(AnimatedJavaExecutor executor, String animationName, int despawnAfterTicks) { + this.executor = executor; + this.animationName = animationName; + this.despawnAfterTicks = despawnAfterTicks; + } + + @Override + public boolean finishedPlaying() { + return true; + } + + @Override + public boolean execute(Train train) { + if(!executor.isSpawned()){ + executor.spawnRig(); + } + executor.playAnimation(animationName); + + if(despawnAfterTicks != -1) + Sync.runAfter(executor::removeRig, despawnAfterTicks); + + return true; + } + + @Override + public boolean executeReversed(Train train) { + return execute(train); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/handle/EffectTriggerHandle.java b/src/main/java/com/jverbruggen/jrides/effect/handle/EffectTriggerHandle.java new file mode 100644 index 00000000..8068693c --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/handle/EffectTriggerHandle.java @@ -0,0 +1,49 @@ +package com.jverbruggen.jrides.effect.handle; + +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.train.CoasterCart; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +import java.util.Iterator; +import java.util.LinkedList; +import java.util.function.Predicate; + +public interface EffectTriggerHandle { + static T FindNearestNextEffect(Class clazz, LinkedList linkedList, Frame forFrame){ + if(linkedList == null || linkedList.size() == 0 || forFrame == null) + return null; + else if(linkedList.size() == 1) + return linkedList.getFirst(); + else{ + T selectedEffect = linkedList.getFirst(); + if(selectedEffect.shouldPlay(forFrame)){ + Iterator iterator = linkedList.iterator(); + while(iterator.hasNext()){ + T comparing = iterator.next(); + if(!comparing.shouldPlay(forFrame) && clazz.isInstance(comparing)){ + selectedEffect = comparing; + break; + } + } + }else{ + Iterator iterator = linkedList.descendingIterator(); + while(iterator.hasNext()){ + T comparing = iterator.next(); + boolean shouldPlay = comparing.shouldPlay(forFrame) && clazz.isInstance(comparing); + boolean isCloser = Frame.isBetweenFrames(forFrame, selectedEffect.getFrame(), comparing.getFrame()); + + if(shouldPlay || isCloser){ + selectedEffect = comparing; + }else break; + } + } + return selectedEffect; + } + } + + Frame getFrame(); + + void execute(Train train, CoasterCart cart); + + boolean shouldPlay(Frame frame); +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/handle/cart/BaseCartEffectTriggerHandle.java b/src/main/java/com/jverbruggen/jrides/effect/handle/cart/BaseCartEffectTriggerHandle.java new file mode 100644 index 00000000..81db7c93 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/handle/cart/BaseCartEffectTriggerHandle.java @@ -0,0 +1,56 @@ +package com.jverbruggen.jrides.effect.handle.cart; + +import com.jverbruggen.jrides.effect.cart.CartEffectTrigger; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.train.CoasterCart; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.Section; + +public abstract class BaseCartEffectTriggerHandle implements CartEffectTriggerHandle { + protected final Frame frame; + protected final CartEffectTrigger cartEffectTrigger; + protected CartEffectTriggerHandle nextCartEffectTriggerHandle; + + public BaseCartEffectTriggerHandle(Frame frame, CartEffectTrigger cartEffectTrigger) { + this.frame = frame; + this.cartEffectTrigger = cartEffectTrigger; + this.nextCartEffectTriggerHandle = null; + } + + @Override + public boolean shouldPlay(Frame forFrame) { + Section section = forFrame.getSection(); + return this.getFrame().getSection().equals(section) + && section.hasPassed(this.getFrame(), forFrame); + } + + @Override + public Frame getFrame() { + return frame; + } + + @Override + public CartEffectTrigger getCartEffectTrigger() { + return cartEffectTrigger; + } + + @Override + public void setNext(CartEffectTriggerHandle cartEffectTriggerHandle) { + nextCartEffectTriggerHandle = cartEffectTriggerHandle; + } + + @Override + public CartEffectTriggerHandle next() { + return nextCartEffectTriggerHandle; + } + + @Override + public String toString() { + return ""; + } + + @Override + public void execute(Train train, CoasterCart cart) { + executeForCart(cart); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/handle/cart/CartEffectTriggerHandle.java b/src/main/java/com/jverbruggen/jrides/effect/handle/cart/CartEffectTriggerHandle.java new file mode 100644 index 00000000..3dc40a1d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/handle/cart/CartEffectTriggerHandle.java @@ -0,0 +1,20 @@ +package com.jverbruggen.jrides.effect.handle.cart; + +import com.jverbruggen.jrides.effect.cart.CartEffectTrigger; +import com.jverbruggen.jrides.effect.handle.EffectTriggerHandle; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.train.CoasterCart; + +public interface CartEffectTriggerHandle extends EffectTriggerHandle { + CartEffectTrigger getCartEffectTrigger(); + + /** + * + * @param cart + * @return true if can process more effects + */ + boolean executeForCart(CoasterCart cart); + + void setNext(CartEffectTriggerHandle cartEffectTriggerHandle); + CartEffectTriggerHandle next(); +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/handle/cart/DefaultCartEffectTriggerHandle.java b/src/main/java/com/jverbruggen/jrides/effect/handle/cart/DefaultCartEffectTriggerHandle.java new file mode 100644 index 00000000..389cde64 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/handle/cart/DefaultCartEffectTriggerHandle.java @@ -0,0 +1,16 @@ +package com.jverbruggen.jrides.effect.handle.cart; + +import com.jverbruggen.jrides.effect.cart.CartEffectTrigger; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.train.CoasterCart; + +public class DefaultCartEffectTriggerHandle extends BaseCartEffectTriggerHandle { + public DefaultCartEffectTriggerHandle(Frame frame, CartEffectTrigger cartEffectTrigger) { + super(frame, cartEffectTrigger); + } + + @Override + public boolean executeForCart(CoasterCart cart) { + return getCartEffectTrigger().execute(cart); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/handle/train/BaseTrainEffectTriggerHandle.java b/src/main/java/com/jverbruggen/jrides/effect/handle/train/BaseTrainEffectTriggerHandle.java new file mode 100644 index 00000000..f67c0391 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/handle/train/BaseTrainEffectTriggerHandle.java @@ -0,0 +1,56 @@ +package com.jverbruggen.jrides.effect.handle.train; + +import com.jverbruggen.jrides.effect.train.TrainEffectTrigger; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.train.CoasterCart; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.Section; + +public abstract class BaseTrainEffectTriggerHandle implements TrainEffectTriggerHandle { + protected final Frame frame; + protected final TrainEffectTrigger trainEffectTrigger; + protected TrainEffectTriggerHandle nextTrainEffectTriggerHandle; + + public BaseTrainEffectTriggerHandle(Frame frame, TrainEffectTrigger trainEffectTrigger) { + this.frame = frame; + this.trainEffectTrigger = trainEffectTrigger; + this.nextTrainEffectTriggerHandle = null; + } + + @Override + public boolean shouldPlay(Frame forFrame) { + Section section = forFrame.getSection(); + return this.getFrame().getSection().equals(section) + && section.hasPassed(this.getFrame(), forFrame); + } + + @Override + public Frame getFrame() { + return frame; + } + + @Override + public TrainEffectTrigger getTrainEffectTrigger() { + return trainEffectTrigger; + } + + @Override + public void setNext(TrainEffectTriggerHandle trainEffectTriggerHandle) { + nextTrainEffectTriggerHandle = trainEffectTriggerHandle; + } + + @Override + public TrainEffectTriggerHandle next() { + return nextTrainEffectTriggerHandle; + } + + @Override + public String toString() { + return ""; + } + + @Override + public void execute(Train train, CoasterCart cart) { + executeForTrain(train); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/handle/train/DefaultTrainEffectTriggerHandle.java b/src/main/java/com/jverbruggen/jrides/effect/handle/train/DefaultTrainEffectTriggerHandle.java new file mode 100644 index 00000000..d082f0d5 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/handle/train/DefaultTrainEffectTriggerHandle.java @@ -0,0 +1,16 @@ +package com.jverbruggen.jrides.effect.handle.train; + +import com.jverbruggen.jrides.effect.train.TrainEffectTrigger; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +public class DefaultTrainEffectTriggerHandle extends BaseTrainEffectTriggerHandle { + public DefaultTrainEffectTriggerHandle(Frame frame, TrainEffectTrigger trainEffectTrigger) { + super(frame, trainEffectTrigger); + } + + @Override + public boolean executeForTrain(Train train) { + return getTrainEffectTrigger().execute(train); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/handle/train/ReversedTrainEffectTriggerHandle.java b/src/main/java/com/jverbruggen/jrides/effect/handle/train/ReversedTrainEffectTriggerHandle.java new file mode 100644 index 00000000..42538e93 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/handle/train/ReversedTrainEffectTriggerHandle.java @@ -0,0 +1,16 @@ +package com.jverbruggen.jrides.effect.handle.train; + +import com.jverbruggen.jrides.effect.train.TrainEffectTrigger; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +public class ReversedTrainEffectTriggerHandle extends BaseTrainEffectTriggerHandle { + public ReversedTrainEffectTriggerHandle(Frame frame, TrainEffectTrigger trainEffectTrigger) { + super(frame, trainEffectTrigger); + } + + @Override + public boolean executeForTrain(Train train) { + return getTrainEffectTrigger().executeReversed(train); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/handle/train/TrainEffectTriggerHandle.java b/src/main/java/com/jverbruggen/jrides/effect/handle/train/TrainEffectTriggerHandle.java new file mode 100644 index 00000000..0dd9af03 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/handle/train/TrainEffectTriggerHandle.java @@ -0,0 +1,21 @@ +package com.jverbruggen.jrides.effect.handle.train; + +import com.jverbruggen.jrides.effect.handle.EffectTriggerHandle; +import com.jverbruggen.jrides.effect.train.TrainEffectTrigger; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +public interface TrainEffectTriggerHandle extends EffectTriggerHandle { + Frame getFrame(); + TrainEffectTrigger getTrainEffectTrigger(); + + /** + * + * @param train + * @return true if can process more effects + */ + boolean executeForTrain(Train train); + + void setNext(TrainEffectTriggerHandle trainEffectTriggerHandle); + TrainEffectTriggerHandle next(); +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/structure/StructureEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/structure/StructureEffectTrigger.java new file mode 100644 index 00000000..6b82834f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/structure/StructureEffectTrigger.java @@ -0,0 +1,75 @@ +package com.jverbruggen.jrides.effect.structure; + +import com.github.shynixn.structureblocklib.api.bukkit.StructureBlockLibApi; +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.effect.entity.common.DelayedEntityTask; +import com.jverbruggen.jrides.effect.train.BaseTrainEffectTrigger; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import org.bukkit.Location; +import org.bukkit.World; + +public class StructureEffectTrigger extends BaseTrainEffectTrigger { + private final Location location; + private final String worldName; + private final String structureIdentifierName; + private final String structureIdentifierAuthor; + + private final DelayedEntityTask delayedEntityTask; + + public StructureEffectTrigger(int delayTicks, Vector3 position, String structureIdentifierName, String structureIdentifierAuthor) { + this.structureIdentifierName = structureIdentifierName; + this.structureIdentifierAuthor = structureIdentifierAuthor; + World world = JRidesPlugin.getWorld(); + + this.location = position.toBukkitLocation(world); + this.worldName = world.getName(); + this.delayedEntityTask = new DelayedEntityTask(this::runTask, delayTicks, 0); + } + + private void runTask(){ + loadStructure(); + } + + private void loadStructure(){ + StructureBlockLibApi.INSTANCE + .loadStructure(JRidesPlugin.getBukkitPlugin()) + .at(location) + .loadFromWorld(worldName, structureIdentifierAuthor, structureIdentifierName) + .onException(e -> JRidesPlugin.getLogger().warning( + "Could not load StructureEffectTrigger, " + + "author: '" + structureIdentifierAuthor + "', " + + "name: '" + structureIdentifierName + "' " + + "for reason: '" + e.getMessage() + "'")); + } + + @Override + public boolean finishedPlaying() { + return delayedEntityTask.isFinished(); + } + + @Override + public boolean execute(Train train) { + if(delayedEntityTask.isBusy()) return true; + + delayedEntityTask.start(); + return true; + } + + @Override + public boolean executeReversed(Train train) { + return execute(train); + } + + public static StructureEffectTrigger createStructureEffectTrigger(int delayTicks, Vector3 position, String structureIdentifier){ + if(!structureIdentifier.contains(":")){ + throw new RuntimeException("Structure identifier should be of format ':'"); + } + + String[] splitIdentifier = structureIdentifier.split(":"); + String structureIdentifierAuthor = splitIdentifier[0]; + String structureIdentifierName = splitIdentifier[1]; + + return new StructureEffectTrigger(delayTicks, position, structureIdentifierName, structureIdentifierAuthor); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/train/BaseTrainEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/train/BaseTrainEffectTrigger.java new file mode 100644 index 00000000..8f505ed2 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/train/BaseTrainEffectTrigger.java @@ -0,0 +1,23 @@ +package com.jverbruggen.jrides.effect.train; + +import com.jverbruggen.jrides.effect.handle.EffectTriggerHandle; +import com.jverbruggen.jrides.effect.handle.train.DefaultTrainEffectTriggerHandle; +import com.jverbruggen.jrides.effect.handle.train.ReversedTrainEffectTriggerHandle; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +public abstract class BaseTrainEffectTrigger implements TrainEffectTrigger { + @Override + public EffectTriggerHandle createHandle(Frame frame, boolean reversed) { + if(reversed) { + return new ReversedTrainEffectTriggerHandle(frame, this); + } else { + return new DefaultTrainEffectTriggerHandle(frame, this); + } + } + + @Override + public boolean executeReversed(Train train) { + return execute(train); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/train/EjectEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/train/EjectEffectTrigger.java new file mode 100644 index 00000000..64ffc223 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/train/EjectEffectTrigger.java @@ -0,0 +1,37 @@ +package com.jverbruggen.jrides.effect.train; + +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.event.player.PlayerFinishedRideEvent; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +import java.util.stream.Collectors; + +public class EjectEffectTrigger extends BaseTrainEffectTrigger { + private final boolean asFinished; + + public EjectEffectTrigger(boolean asFinished) { + this.asFinished = asFinished; + } + + @Override + public boolean finishedPlaying() { + return true; + } + + @Override + public boolean execute(Train train) { + if(asFinished) + PlayerFinishedRideEvent.sendFinishedRideEvent(train.getPassengers() + .stream() + .map(p -> (JRidesPlayer)p) + .collect(Collectors.toList()), train.getHandle().getCoasterHandle().getRide()); + + train.ejectPassengers(); + return true; + } + + @Override + public boolean executeReversed(Train train) { + return execute(train); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/train/ResetEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/train/ResetEffectTrigger.java new file mode 100644 index 00000000..ef6bd3ec --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/train/ResetEffectTrigger.java @@ -0,0 +1,22 @@ +package com.jverbruggen.jrides.effect.train; + +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import org.bukkit.Bukkit; + +public class ResetEffectTrigger extends BaseTrainEffectTrigger { + @Override + public boolean finishedPlaying() { + return true; + } + + @Override + public boolean execute(Train train) { + train.reset(); + return false; + } + + @Override + public boolean executeReversed(Train train) { + return execute(train); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/train/SequenceTrainEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/train/SequenceTrainEffectTrigger.java new file mode 100644 index 00000000..75c9b1fb --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/train/SequenceTrainEffectTrigger.java @@ -0,0 +1,117 @@ +package com.jverbruggen.jrides.effect.train; + +import com.jverbruggen.jrides.effect.entity.EntityMovementTrigger; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +import java.util.List; + +public class SequenceTrainEffectTrigger extends BaseTrainEffectTrigger { + private final List triggerSequence; + + private Train cachedTrain; + private boolean reversed; + private boolean started; + private boolean finished; + private boolean shouldRunNext; + private boolean running; + private int triggerPointer; + + public SequenceTrainEffectTrigger(List triggerSequence){ + this.triggerSequence = triggerSequence; + this.cachedTrain = null; + this.reversed = false; + this.started = false; + this.finished = false; + this.shouldRunNext = false; + this.running = false; + this.triggerPointer = 0; + } + + @Override + public boolean finishedPlaying() { + return finished; + } + + private void finish(){ + finished = true; + started = false; + } + + private void onItemFinish(){ + runNext(); + } + + private void runNext(){ + if(finishedPlaying()) return; + + if(running){ + shouldRunNext = true; + return; + } + + shouldRunNext = true; + running = true; + + while(shouldRunNext){ + shouldRunNext = false; + + if(reachedEnd()){ + finish(); + return; + } + + EntityMovementTrigger trigger = triggerSequence.get(triggerPointer); + trigger.onFinish(this::onItemFinish); + + if(reversed){ + trigger.executeReversed(cachedTrain); + }else{ + trigger.execute(cachedTrain); + } + + incrementPointer(); + } + + running = false; + } + + private boolean reachedEnd(){ + if(!reversed) return triggerPointer >= triggerSequence.size(); + else return triggerPointer < 0; + } + + private void incrementPointer(){ + if(!reversed) triggerPointer++; + else triggerPointer--; + } + + private void start(Train train){ + if(this.started) return; + + this.triggerPointer = this.reversed ? this.triggerSequence.size()-1 : 0; + this.cachedTrain = train; + this.started = true; + this.finished = false; + this.running = false; + + runNext(); + } + + @Override + public boolean execute(Train train) { + if(this.started) return true; + + this.reversed = false; + start(train); + return true; + } + + @Override + public boolean executeReversed(Train train) { + if(this.started) return true; + + this.reversed = true; + start(train); + return true; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/train/TrainEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/train/TrainEffectTrigger.java new file mode 100644 index 00000000..68848d4b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/train/TrainEffectTrigger.java @@ -0,0 +1,20 @@ +package com.jverbruggen.jrides.effect.train; + +import com.jverbruggen.jrides.effect.EffectTrigger; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +public interface TrainEffectTrigger extends EffectTrigger { + /** + * + * @param train + * @return true if can process more effects + */ + boolean execute(Train train); + + /** + * + * @param train + * @return true if can process more effects + */ + boolean executeReversed(Train train); +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/train/cart/AllCartsTrainEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/train/cart/AllCartsTrainEffectTrigger.java new file mode 100644 index 00000000..1eb00dcf --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/train/cart/AllCartsTrainEffectTrigger.java @@ -0,0 +1,29 @@ +package com.jverbruggen.jrides.effect.train.cart; + +import com.jverbruggen.jrides.effect.cart.CartEffectTrigger; +import com.jverbruggen.jrides.effect.train.BaseTrainEffectTrigger; +import com.jverbruggen.jrides.effect.train.TrainEffectTrigger; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +public class AllCartsTrainEffectTrigger extends BaseTrainEffectTrigger implements TrainEffectTrigger { + private final CartEffectTrigger cartEffectTrigger; + + public AllCartsTrainEffectTrigger(CartEffectTrigger cartEffectTrigger) { + this.cartEffectTrigger = cartEffectTrigger; + } + + @Override + public boolean execute(Train train) { + return train.getCarts().stream().allMatch(cartEffectTrigger::execute); + } + + @Override + public boolean executeReversed(Train train) { + return train.getCarts().stream().allMatch(cartEffectTrigger::executeReversed); + } + + @Override + public boolean finishedPlaying() { + return true; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/train/external/ExternalEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/train/external/ExternalEffectTrigger.java new file mode 100644 index 00000000..cb577126 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/train/external/ExternalEffectTrigger.java @@ -0,0 +1,34 @@ +package com.jverbruggen.jrides.effect.train.external; + +import com.jverbruggen.jrides.effect.train.BaseTrainEffectTrigger; +import com.jverbruggen.jrides.event.ride.ExternalTriggerEvent; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.plugin.PluginManager; + +import java.util.Map; + +public class ExternalEffectTrigger extends BaseTrainEffectTrigger { + private final Map data; + + public ExternalEffectTrigger(Map data) { + this.data = data; + } + + @Override + public boolean finishedPlaying() { + return true; + } + + @Override + public boolean execute(Train train) { + PluginManager pluginManager = ServiceProvider.getSingleton(PluginManager.class); + pluginManager.callEvent(new ExternalTriggerEvent(train.getName(), data)); + return true; + } + + @Override + public boolean executeReversed(Train train) { + return execute(train); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/train/music/ExternalMusicEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/train/music/ExternalMusicEffectTrigger.java new file mode 100644 index 00000000..04c02e41 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/train/music/ExternalMusicEffectTrigger.java @@ -0,0 +1,52 @@ +package com.jverbruggen.jrides.effect.train.music; + +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.effect.train.BaseTrainEffectTrigger; +import com.jverbruggen.jrides.event.ride.OnrideMusicTriggerEvent; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.plugin.PluginManager; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class ExternalMusicEffectTrigger extends BaseTrainEffectTrigger implements MusicEffectTrigger { + private final PluginManager pluginManager; + private final String resource; + private final String descriptor; + + public ExternalMusicEffectTrigger(String resource, String descriptor) { + this.pluginManager = ServiceProvider.getSingleton(PluginManager.class); + this.resource = resource; + this.descriptor = descriptor; + } + + @Override + public boolean execute(Train train) { + List passengers; + if(train != null){ + passengers = train.getPassengers(); + }else{ + passengers = new ArrayList<>(); + } + + pluginManager.callEvent(new OnrideMusicTriggerEvent(passengers + .stream() + .map(p -> (JRidesPlayer)p) + .collect(Collectors.toList()), resource, descriptor)); + + return true; + } + + @Override + public boolean finishedPlaying() { + return true; + } + + @Override + public String toString() { + return ""; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/effect/train/music/MusicEffectTrigger.java b/src/main/java/com/jverbruggen/jrides/effect/train/music/MusicEffectTrigger.java new file mode 100644 index 00000000..4b44237d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/effect/train/music/MusicEffectTrigger.java @@ -0,0 +1,6 @@ +package com.jverbruggen.jrides.effect.train.music; + +import com.jverbruggen.jrides.effect.train.TrainEffectTrigger; + +public interface MusicEffectTrigger extends TrainEffectTrigger { +} diff --git a/src/main/java/com/jverbruggen/jrides/event/action/OperateRideAction.java b/src/main/java/com/jverbruggen/jrides/event/action/OperateRideAction.java new file mode 100644 index 00000000..3f22bea8 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/event/action/OperateRideAction.java @@ -0,0 +1,35 @@ +package com.jverbruggen.jrides.event.action; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.common.MenuSessionManager; +import com.jverbruggen.jrides.common.Sync; +import com.jverbruggen.jrides.language.FeedbackType; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.menu.Menu; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.inventory.Inventory; + +public class OperateRideAction implements RideAction { + @Override + public void accept(VirtualEntity virtualEntity, RideHandle rideHandle, Player player) { + Sync.runSynced(() -> acceptInternal(rideHandle, player)); + } + + private void acceptInternal(RideHandle rideHandle, Player player){ + MenuSessionManager menuSessionManager = ServiceProvider.getSingleton(MenuSessionManager.class); + LanguageFile languageFile = ServiceProvider.getSingleton(LanguageFile.class); + + Menu rideControlMenu = rideHandle.getRideControlMenu(); + if(rideControlMenu == null){ + languageFile.sendMessage(player, LanguageFileField.ERROR_RIDE_CONTROL_MENU_NOT_FOUND, FeedbackType.CONFLICT); + return; + } + Inventory inventory = rideControlMenu.getInventoryFor(player); + + menuSessionManager.addOpenMenu(player, rideControlMenu, inventory); + player.getBukkitPlayer().openInventory(inventory); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/event/action/RideAction.java b/src/main/java/com/jverbruggen/jrides/event/action/RideAction.java new file mode 100644 index 00000000..d47fe91b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/event/action/RideAction.java @@ -0,0 +1,10 @@ +package com.jverbruggen.jrides.event.action; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.VirtualEntity; + +public interface RideAction { + + void accept(VirtualEntity virtualEntity, RideHandle rideHandle, Player player); +} diff --git a/src/main/java/com/jverbruggen/jrides/event/player/PlayerFinishedRideEvent.java b/src/main/java/com/jverbruggen/jrides/event/player/PlayerFinishedRideEvent.java new file mode 100644 index 00000000..8698fe4d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/event/player/PlayerFinishedRideEvent.java @@ -0,0 +1,44 @@ +package com.jverbruggen.jrides.event.player; + +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.api.JRidesRide; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.PluginManager; + +import java.util.List; + +public class PlayerFinishedRideEvent extends Event { + private static final HandlerList HANDLERS = new HandlerList(); + private final JRidesPlayer player; + private final JRidesRide ride; + + public PlayerFinishedRideEvent(JRidesPlayer player, JRidesRide ride) { + this.player = player; + this.ride = ride; + } + + public JRidesPlayer getPlayer() { + return player; + } + + public JRidesRide getRide() { + return ride; + } + + public static HandlerList getHandlerList() { + return HANDLERS; + } + + @Override + public HandlerList getHandlers() { + return HANDLERS; + } + + public static void sendFinishedRideEvent(List players, JRidesRide ride){ + PluginManager pluginManager = ServiceProvider.getSingleton(PluginManager.class); + players.forEach(p -> pluginManager.callEvent(new PlayerFinishedRideEvent(p, ride))); + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/event/player/PlayerJoinEvent.java b/src/main/java/com/jverbruggen/jrides/event/player/PlayerJoinEvent.java new file mode 100644 index 00000000..1341bd09 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/event/player/PlayerJoinEvent.java @@ -0,0 +1,37 @@ +package com.jverbruggen.jrides.event.player; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.Bukkit; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.PluginManager; + +public class PlayerJoinEvent extends Event { + private static final HandlerList HANDLERS = new HandlerList(); + private final JRidesPlayer player; + + public PlayerJoinEvent(JRidesPlayer player) { + this.player = player; + } + + public JRidesPlayer getPlayer() { + return player; + } + + public static HandlerList getHandlerList() { + return HANDLERS; + } + + @Override + public HandlerList getHandlers() { + return HANDLERS; + } + + public static void send(JRidesPlayer player){ + PluginManager pluginManager = ServiceProvider.getSingleton(PluginManager.class); + Bukkit.getScheduler().runTask(JRidesPlugin.getBukkitPlugin(), + () -> pluginManager.callEvent(new PlayerJoinEvent(player))); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/event/player/PlayerQuitEvent.java b/src/main/java/com/jverbruggen/jrides/event/player/PlayerQuitEvent.java new file mode 100644 index 00000000..8bceb623 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/event/player/PlayerQuitEvent.java @@ -0,0 +1,37 @@ +package com.jverbruggen.jrides.event.player; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.Bukkit; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.PluginManager; + +public class PlayerQuitEvent extends Event { + private static final HandlerList HANDLERS = new HandlerList(); + private final JRidesPlayer player; + + public PlayerQuitEvent(JRidesPlayer player) { + this.player = player; + } + + public JRidesPlayer getPlayer() { + return player; + } + + public static HandlerList getHandlerList() { + return HANDLERS; + } + + @Override + public HandlerList getHandlers() { + return HANDLERS; + } + + public static void send(JRidesPlayer player){ + PluginManager pluginManager = ServiceProvider.getSingleton(PluginManager.class); + Bukkit.getScheduler().runTask(JRidesPlugin.getBukkitPlugin(), + () -> pluginManager.callEvent(new PlayerQuitEvent(player))); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/event/player/PlayerSitDownEvent.java b/src/main/java/com/jverbruggen/jrides/event/player/PlayerSitDownEvent.java new file mode 100644 index 00000000..a5439a8e --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/event/player/PlayerSitDownEvent.java @@ -0,0 +1,45 @@ +package com.jverbruggen.jrides.event.player; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.models.ride.Ride; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.Bukkit; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.PluginManager; + +public class PlayerSitDownEvent extends Event { + private static final HandlerList HANDLERS = new HandlerList(); + private final org.bukkit.entity.Player player; + private final String rideIdentifier; + + public PlayerSitDownEvent(org.bukkit.entity.Player player, String rideIdentifier) { + this.player = player; + this.rideIdentifier = rideIdentifier; + } + + public org.bukkit.entity.Player getPlayer() { + return player; + } + + public String getRideIdentifier() { + return rideIdentifier; + } + + public static HandlerList getHandlerList() { + return HANDLERS; + } + + @Override + public HandlerList getHandlers() { + return HANDLERS; + } + + public static void send(JRidesPlayer player, Ride ride){ + PluginManager pluginManager = ServiceProvider.getSingleton(PluginManager.class); + Bukkit.getScheduler().runTask(JRidesPlugin.getBukkitPlugin(), + () -> pluginManager.callEvent(new PlayerSitDownEvent(player.getBukkitPlayer(), ride.getIdentifier()))); + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/event/player/PlayerStandUpEvent.java b/src/main/java/com/jverbruggen/jrides/event/player/PlayerStandUpEvent.java new file mode 100644 index 00000000..ceaa3627 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/event/player/PlayerStandUpEvent.java @@ -0,0 +1,45 @@ +package com.jverbruggen.jrides.event.player; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.models.ride.Ride; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.Bukkit; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.PluginManager; + +public class PlayerStandUpEvent extends Event { + private static final HandlerList HANDLERS = new HandlerList(); + private final org.bukkit.entity.Player player; + private final String rideIdentifier; + + public PlayerStandUpEvent(org.bukkit.entity.Player player, String rideIdentifier) { + this.player = player; + this.rideIdentifier = rideIdentifier; + } + + public org.bukkit.entity.Player getPlayer() { + return player; + } + + public String getRideIdentifier() { + return rideIdentifier; + } + + public static HandlerList getHandlerList() { + return HANDLERS; + } + + @Override + public HandlerList getHandlers() { + return HANDLERS; + } + + public static void send(JRidesPlayer player, Ride ride){ + PluginManager pluginManager = ServiceProvider.getSingleton(PluginManager.class); + Bukkit.getScheduler().runTask(JRidesPlugin.getBukkitPlugin(), + () -> pluginManager.callEvent(new PlayerStandUpEvent(player.getBukkitPlayer(), ride.getIdentifier()))); + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/event/player/PlayerTeleportByJRidesEvent.java b/src/main/java/com/jverbruggen/jrides/event/player/PlayerTeleportByJRidesEvent.java new file mode 100644 index 00000000..47276ebc --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/event/player/PlayerTeleportByJRidesEvent.java @@ -0,0 +1,60 @@ +package com.jverbruggen.jrides.event.player; + +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.api.JRidesPlayerLocation; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.PluginManager; + +public class PlayerTeleportByJRidesEvent extends Event implements Cancellable { + private static final HandlerList HANDLERS = new HandlerList(); + private final JRidesPlayer player; + private final JRidesPlayerLocation location; + private boolean cancelled; + private boolean hard; + + public PlayerTeleportByJRidesEvent(JRidesPlayer player, JRidesPlayerLocation location, boolean hard) { + this.player = player; + this.location = location; + this.cancelled = false; + this.hard = hard; + } + + public JRidesPlayer getPlayer() { + return player; + } + + public JRidesPlayerLocation getLocation() { + return location; + } + + public boolean isHardTeleport() { + return hard; + } + + public static HandlerList getHandlerList() { + return HANDLERS; + } + + @Override + public HandlerList getHandlers() { + return HANDLERS; + } + + public static void sendEvent(JRidesPlayer player, JRidesPlayerLocation playerLocation, boolean hard){ + PluginManager pluginManager = ServiceProvider.getSingleton(PluginManager.class); + pluginManager.callEvent(new PlayerTeleportByJRidesEvent(player, playerLocation, hard)); + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean b) { + cancelled = b; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/event/ride/ExternalTriggerEvent.java b/src/main/java/com/jverbruggen/jrides/event/ride/ExternalTriggerEvent.java new file mode 100644 index 00000000..08078e56 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/event/ride/ExternalTriggerEvent.java @@ -0,0 +1,34 @@ +package com.jverbruggen.jrides.event.ride; + +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import java.util.Map; + +public class ExternalTriggerEvent extends Event { + private static final HandlerList HANDLERS = new HandlerList(); + private final String trainName; + private final Map data; + + public ExternalTriggerEvent(String trainName, Map data) { + this.trainName = trainName; + this.data = data; + } + + public static HandlerList getHandlerList() { + return HANDLERS; + } + + public String getTrainName() { + return trainName; + } + + public Map getData() { + return data; + } + + @Override + public HandlerList getHandlers() { + return HANDLERS; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/event/ride/OnrideMusicTriggerEvent.java b/src/main/java/com/jverbruggen/jrides/event/ride/OnrideMusicTriggerEvent.java new file mode 100644 index 00000000..a4136816 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/event/ride/OnrideMusicTriggerEvent.java @@ -0,0 +1,41 @@ +package com.jverbruggen.jrides.event.ride; + +import com.jverbruggen.jrides.api.JRidesPlayer; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import java.util.List; + +public class OnrideMusicTriggerEvent extends Event { + private static final HandlerList HANDLERS = new HandlerList(); + private final List players; + private final String resource; + private final String descriptor; + + public OnrideMusicTriggerEvent(List players, String resource, String descriptor) { + this.players = players; + this.resource = resource; + this.descriptor = descriptor; + } + + public static HandlerList getHandlerList() { + return HANDLERS; + } + + public List getPlayers(){ + return players; + } + + public String getResource() { + return resource; + } + + public String getDescriptor() { + return descriptor; + } + + @Override + public HandlerList getHandlers() { + return HANDLERS; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/event/ride/RideFinishedEvent.java b/src/main/java/com/jverbruggen/jrides/event/ride/RideFinishedEvent.java new file mode 100644 index 00000000..5b1ecdb4 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/event/ride/RideFinishedEvent.java @@ -0,0 +1,45 @@ +package com.jverbruggen.jrides.event.ride; + +import com.jverbruggen.jrides.api.JRidesRide; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.PluginManager; + +import java.util.List; + + +public class RideFinishedEvent extends Event { + private static final HandlerList HANDLERS = new HandlerList(); + + private final JRidesRide ride; + private final List players; + + public RideFinishedEvent(JRidesRide ride, List players) { + this.ride = ride; + this.players = players; + } + + public JRidesRide getRide() { + return ride; + } + + public List getPlayers() { + return players; + } + + public static HandlerList getHandlerList() { + return HANDLERS; + } + + @Override + public HandlerList getHandlers() { + return HANDLERS; + } + + public static void send(JRidesRide ride, List players) { + PluginManager pluginManager = ServiceProvider.getSingleton(PluginManager.class); + pluginManager.callEvent(new RideFinishedEvent(ride, players)); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/event/ride/RideInitializedEvent.java b/src/main/java/com/jverbruggen/jrides/event/ride/RideInitializedEvent.java new file mode 100644 index 00000000..ddcba4c2 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/event/ride/RideInitializedEvent.java @@ -0,0 +1,27 @@ +package com.jverbruggen.jrides.event.ride; + +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.PluginManager; + +public class RideInitializedEvent extends Event { + /** + * Sent when system is done initializing all rides + */ + private static final HandlerList HANDLERS = new HandlerList(); + + public static HandlerList getHandlerList() { + return HANDLERS; + } + + @Override + public HandlerList getHandlers() { + return HANDLERS; + } + + public static void send(){ + PluginManager pluginManager = ServiceProvider.getSingleton(PluginManager.class); + pluginManager.callEvent(new RideInitializedEvent()); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/event/ride/RideStateUpdatedEvent.java b/src/main/java/com/jverbruggen/jrides/event/ride/RideStateUpdatedEvent.java new file mode 100644 index 00000000..7de2bbdb --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/event/ride/RideStateUpdatedEvent.java @@ -0,0 +1,51 @@ +package com.jverbruggen.jrides.event.ride; + +import com.jverbruggen.jrides.api.JRidesRide; +import com.jverbruggen.jrides.config.ride.RideState; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.plugin.PluginManager; + +public class RideStateUpdatedEvent extends Event { + /** + * Sent when system is done initializing all rides + */ + private static final HandlerList HANDLERS = new HandlerList(); + + public static HandlerList getHandlerList() { + return HANDLERS; + } + + private final JRidesRide ride; + private final RideState newState; + + public RideStateUpdatedEvent(JRidesRide ride, RideState newState) { + this.ride = ride; + this.newState = newState; + } + + public JRidesRide getRide() { + return ride; + } + + public RideState getNewState() { + return newState; + } + + public RideStateUpdatedEvent(boolean isAsync, JRidesRide ride, RideState newState) { + super(isAsync); + this.ride = ride; + this.newState = newState; + } + + @Override + public HandlerList getHandlers() { + return HANDLERS; + } + + public static void send(JRidesRide ride, RideState newState){ + PluginManager pluginManager = ServiceProvider.getSingleton(PluginManager.class); + pluginManager.callEvent(new RideStateUpdatedEvent(ride, newState)); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/exception/CoasterLoadException.java b/src/main/java/com/jverbruggen/jrides/exception/CoasterLoadException.java new file mode 100644 index 00000000..197a3f3e --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/exception/CoasterLoadException.java @@ -0,0 +1,11 @@ +package com.jverbruggen.jrides.exception; + +public class CoasterLoadException extends Exception { + public CoasterLoadException(String s){ + super("Coaster could not load: " + s); + } + + public CoasterLoadException(){ + super("Coaster could not load because something went wrong during initialization"); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/exception/NoTrackSpecifiedException.java b/src/main/java/com/jverbruggen/jrides/exception/NoTrackSpecifiedException.java new file mode 100644 index 00000000..471704ad --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/exception/NoTrackSpecifiedException.java @@ -0,0 +1,11 @@ +package com.jverbruggen.jrides.exception; + +public class NoTrackSpecifiedException extends CoasterLoadException { + public NoTrackSpecifiedException(){ + super("No track was specified in coaster.yml"); + } + + public NoTrackSpecifiedException(String s){ + super("No track specified: " + s); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/items/ItemStackFactory.java b/src/main/java/com/jverbruggen/jrides/items/ItemStackFactory.java new file mode 100644 index 00000000..734c8ff3 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/items/ItemStackFactory.java @@ -0,0 +1,61 @@ +package com.jverbruggen.jrides.items; + +import com.jverbruggen.jrides.config.coaster.objects.item.ItemStackConfig; +import com.jverbruggen.jrides.models.entity.Player; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.SkullMeta; + +import java.util.List; + +import javax.annotation.Nullable; + +public class ItemStackFactory { + public static ItemStack getCoasterStack(Material material, Integer damageValue, boolean unbreakable) { + return getStack(material, damageValue, unbreakable, ChatColor.GOLD + "jrides model", null); + } + + public static ItemStack getStack(Material material, Integer damageValue, boolean unbreakable, String displayName, @Nullable List lore) { + ItemStack stack = new ItemStack(material, 1); + ItemMeta meta = stack.getItemMeta(); + ((Damageable)meta).setDamage(damageValue); + meta.setDisplayName(displayName); + meta.setUnbreakable(unbreakable); + if(lore != null) meta.setLore(lore); + stack.setItemMeta(meta); + return stack; + } + + public static ItemStack getCoasterStackFromConfig(ItemStackConfig itemStackConfig){ + return getCoasterStack(itemStackConfig.getMaterial(), itemStackConfig.getDamage(), itemStackConfig.isUnbreakable()); + } + + public static ItemStack getRideControlButtonStack(Material material, String displayName){ + return getRideControlButtonStack(material, displayName, null, 1); + } + + public static ItemStack getRideControlButtonStack(Material material, String displayName, List lores){ + return getRideControlButtonStack(material, displayName, lores, 1); + } + + public static ItemStack getRideControlButtonStack(Material material, String displayName, List lores, int amount){ + ItemStack stack = new ItemStack(material, amount); + ItemMeta meta = stack.getItemMeta(); + meta.setDisplayName(displayName); + if(lores != null) meta.setLore(lores); + stack.setItemMeta(meta); + return stack; + } + + public static ItemStack getPlayerHead(Player player, String displayName){ + ItemStack stack = new ItemStack(Material.PLAYER_HEAD, 1); + SkullMeta skullMeta = (SkullMeta) stack.getItemMeta(); + skullMeta.setOwningPlayer(player.getBukkitPlayer()); + skullMeta.setDisplayName(displayName); + stack.setItemMeta(skullMeta); + return stack; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/language/FeedbackType.java b/src/main/java/com/jverbruggen/jrides/language/FeedbackType.java new file mode 100644 index 00000000..dfbd0a76 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/language/FeedbackType.java @@ -0,0 +1,8 @@ +package com.jverbruggen.jrides.language; + +public enum FeedbackType { + INFO, + WARNING, + SEVERE, + CONFLICT +} diff --git a/src/main/java/com/jverbruggen/jrides/language/LanguageFile.java b/src/main/java/com/jverbruggen/jrides/language/LanguageFile.java new file mode 100644 index 00000000..2cf03500 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/language/LanguageFile.java @@ -0,0 +1,267 @@ +package com.jverbruggen.jrides.language; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.config.ConfigManager; +import com.jverbruggen.jrides.logging.JRidesLogger; +import com.jverbruggen.jrides.models.entity.MessageReceiver; +import com.jverbruggen.jrides.models.entity.SimpleMessageReceiver; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; + +import javax.annotation.Nonnull; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; + +public class LanguageFile { + private final ConfigManager configManager; + private final JRidesLogger logger; + private FeedbackType defaultFeedbackType = FeedbackType.INFO; + private Map language; + + public LanguageFile() { + this.configManager = ServiceProvider.getSingleton(ConfigManager.class); + this.logger = ServiceProvider.getSingleton(JRidesLogger.class); + this.language = new HashMap<>(); + + // Start of language definitions (do not edit this line) + + setLanguageDefault(LanguageFileField.CHAT_FEEDBACK_PREFIX, "[jrides] "); + setLanguageDefault(LanguageFileField.CHAT_FEEDBACK_INFO_COLOR, "&7"); + setLanguageDefault(LanguageFileField.CHAT_FEEDBACK_WARNING_COLOR, "&e"); + setLanguageDefault(LanguageFileField.CHAT_FEEDBACK_SEVERE_COLOR, "&c"); + + setLanguageDefault(LanguageFileField.COMMAND_RIDE_DISPATCHED_MESSAGE, "Ride %" + LanguageFileTag.rideDisplayName + "% was dispatched!"); + + setLanguageDefault(LanguageFileField.COMMAND_VISUALIZE_ADDED_VIEWER, "You are now viewing %" + LanguageFileTag.rideIdentifier + "% in visualize mode"); + setLanguageDefault(LanguageFileField.COMMAND_VISUALIZE_REMOVED_VIEWER, "You are no longer viewing %" + LanguageFileTag.rideIdentifier + "% in visualize mode"); + + setLanguageDefault(LanguageFileField.NOTIFICATION_PLUGIN_STILL_LOADING, "Please try again later when jrides is loaded"); + + setLanguageDefault(LanguageFileField.NOTIFICATION_RIDE_CONTROL_ACTIVE, "You are now controlling %" + LanguageFileTag.rideDisplayName + "%"); + setLanguageDefault(LanguageFileField.NOTIFICATION_RIDE_CONTROL_INACTIVE, "You are no longer controlling %" + LanguageFileTag.rideDisplayName + "%"); + + setLanguageDefault(LanguageFileField.NOTIFICATION_RIDE_DISPATCH_PROBLEMS, "Cannot dispatch due to the following problems:"); + setLanguageDefault(LanguageFileField.NOTIFICATION_RIDE_NO_TRAIN_PRESENT, "No train present in station"); + setLanguageDefault(LanguageFileField.NOTIFICATION_RIDE_NEXT_BLOCK_OCCUPIED, "Next block section is occupied"); + setLanguageDefault(LanguageFileField.NOTIFICATION_RIDE_WAITING_TIME, "Waiting time has not passed yet"); + setLanguageDefault(LanguageFileField.NOTIFICATION_RIDE_RESTRAINTS_NOT_CLOSED, "Not all restraints are closed"); + setLanguageDefault(LanguageFileField.NOTIFICATION_RIDE_GATES_NOT_CLOSED, "Not all gates are closed"); + setLanguageDefault(LanguageFileField.NOTIFICATION_RIDE_GATE_NOT_CLOSED, "Gate %" + LanguageFileTag.name + "% is not closed"); + + setLanguageDefault(LanguageFileField.NOTIFICATION_RIDE_COUNTER_UPDATE, "\nYou've ridden %" + LanguageFileTag.rideDisplayName + "% %" + LanguageFileTag.rideCount + "% times now\n"); + setLanguageDefault(LanguageFileField.NOTIFICATION_RIDE_STATE_OPEN, "%" + LanguageFileTag.rideDisplayName + "% is now open"); + setLanguageDefault(LanguageFileField.NOTIFICATION_RIDE_STATE_CLOSED, "%" + LanguageFileTag.rideDisplayName + "% is now closed"); + + setLanguageDefault(LanguageFileField.NOTIFICATION_SHIFT_EXIT_CONFIRMATION, "Press shift again within 2 seconds to confirm exiting the ride"); + setLanguageDefault(LanguageFileField.NOTIFICATION_SHIFT_EXIT_CONFIRMED, "You just exited the ride while the restraints were closed"); + setLanguageDefault(LanguageFileField.NOTIFICATION_DISPATCH_WAIT_GENERIC, "Please wait until the ride is dispatched"); + setLanguageDefault(LanguageFileField.NOTIFICATION_DISPATCH_WAIT_SPECIFIC, "Waiting time: %" + LanguageFileTag.time + "% seconds"); + setLanguageDefault(LanguageFileField.NOTIFICATION_RESTRAINT_ON_EXIT_ATTEMPT, "The restraints are closed"); + setLanguageDefault(LanguageFileField.NOTIFICATION_RESTRAINT_ON_ENTER_ATTEMPT, "The restraints are closed"); + setLanguageDefault(LanguageFileField.NOTIFICATION_RESTRAINT_ENTER_OVERRIDE, "You just entered the ride while the restraints were closed"); + setLanguageDefault(LanguageFileField.NOTIFICATION_CANNOT_ENTER_RIDE, "You currently cannot enter this ride, try again later"); + setLanguageDefault(LanguageFileField.NOTIFICATION_CANNOT_ENTER_RIDE_CLOSED, "This ride is currently closed"); + + setLanguageDefault(LanguageFileField.NOTIFICATION_OPERATOR_IDLE_TOO_LONG, "You were idle for too long while operating %" + LanguageFileTag.rideDisplayName + "%"); + setLanguageDefault(LanguageFileField.NOTIFICATION_WARPED, ""); + + setLanguageDefault(LanguageFileField.ELEVATED_OPERATOR_OVERRIDE_VICTIM_MESSAGE, "Player %" + LanguageFileTag.player + "% took over control of the operating cabin"); + + setLanguageDefault(LanguageFileField.ERROR_SMOOTH_COASTERS_DISABLED, "Smoother ride experience is disabled, please install SmoothCoasters"); + setLanguageDefault(LanguageFileField.ERROR_GENERAL_NO_PERMISSION_MESSAGE, "You do not have permissions to execute this action"); + setLanguageDefault(LanguageFileField.ERROR_PLAYER_COMMAND_ONLY_MESSAGE, "Only players can execute this command"); + setLanguageDefault(LanguageFileField.ERROR_UNKNOWN_COMMAND_MESSAGE, "Unknown jrides command. Type '/jrides help' for help"); + setLanguageDefault(LanguageFileField.ERROR_OPERATING_CABIN_OCCUPIED, "You can not take this operating cabin since it is already in use by another operator"); + setLanguageDefault(LanguageFileField.ERROR_OPERATING_NO_PERMISSION, "You are not allowed to operate this ride"); + setLanguageDefault(LanguageFileField.ERROR_RIDE_CONTROL_MENU_NOT_FOUND, "Ride control menu was not found"); + setLanguageDefault(LanguageFileField.ERROR_RIDE_OVERVIEW_MAP_NOT_FOUND, "Could not retrieve map for ride %" + LanguageFileTag.rideIdentifier + "%, was the map id configured?"); + + setLanguageDefault(LanguageFileField.MENU_RIDE_OVERVIEW_TITLE, "Ride overview menu"); + setLanguageDefault(LanguageFileField.MENU_RIDE_OVERVIEW_STATUS_OPEN, "This ride is currently opened"); + setLanguageDefault(LanguageFileField.MENU_RIDE_OVERVIEW_STATUS_CLOSED, "This ride is currently closed"); + setLanguageDefault(LanguageFileField.MENU_RIDE_OVERVIEW_STATUS_MAINTENANCE, "This ride is in maintenance"); + setLanguageDefault(LanguageFileField.MENU_RIDE_CONTROL_TITLE, "Ride control menu"); + setLanguageDefault(LanguageFileField.MENU_ADMIN_RIDE_CONTROL_TITLE, "Admin ride control menu"); + + setLanguageDefault(LanguageFileField.BUTTON_CLAIM_CABIN, "Claim operating cabin"); + setLanguageDefault(LanguageFileField.BUTTON_CABIN_CLAIMED, "Claim operating cabin"); + setLanguageDefault(LanguageFileField.BUTTON_DISPATCH_STATE, "Dispatch"); + setLanguageDefault(LanguageFileField.BUTTON_DISPATCH_PROBLEM_STATE, "Not allowed"); + setLanguageDefault(LanguageFileField.BUTTON_PROBLEMS_STATE, "Problems"); + setLanguageDefault(LanguageFileField.BUTTON_GATES_OPEN_STATE, "Gates are open"); + setLanguageDefault(LanguageFileField.BUTTON_GATES_CLOSED_STATE, "Gates are closed"); + setLanguageDefault(LanguageFileField.BUTTON_RESTRAINTS_OPEN_STATE, "Restraints are open"); + setLanguageDefault(LanguageFileField.BUTTON_RESTRAINTS_CLOSED_STATE, "Restraints are closed"); + + // End of language definitions (do not edit this line) + + fillOverrides(); + } + + private void setLanguageDefault(LanguageFileField field, String _default){ + this.language.put(field, _default); + } + + private void fillOverrides(){ + Map languageOverrides = configManager.getLanguageFile(); + if(languageOverrides == null){ + logger.info("language.yml file was not found."); + return; + } + + for(Map.Entry entry : languageOverrides.entrySet()){ + String keyString = entry.getKey(); + LanguageFileField field; + try{ + field = LanguageFileField.valueOf(keyString); + }catch (IllegalArgumentException e){ + JRidesPlugin.getLogger().severe("Could not override language field " + keyString + " because it does not exist"); + return; + } + + String overrideValue = entry.getValue(); + overrideValue = ChatColor.translateAlternateColorCodes('&', overrideValue); + + language.put(field, overrideValue); + } + + this.logger.info("Loaded language file with " + languageOverrides.size() + " overrides"); + } + + public @Nonnull String get(@Nonnull LanguageFileField field){ + return get(field, null); + } + + public @Nonnull String get(@Nonnull LanguageFileField field, Function builderFunction){ + StringReplacementBuilder builder = new StringReplacementBuilder(); + if(builderFunction != null) builder = builderFunction.apply(builder); + + String value = language.get(field); + if(value == null) + throw new RuntimeException("Language value for language field " + field + " could not be found"); + + value = builder.apply(value); + + return value; + } + + public void sendMessage(MessageReceiver messageReceiver, @Nonnull LanguageFileField field){ + sendMessage(messageReceiver, field, defaultFeedbackType, null); + } + + public void sendMessage(MessageReceiver messageReceiver, @Nonnull String content){ + sendMessage(messageReceiver, content, defaultFeedbackType, null); + } + + public void sendMessage(MessageReceiver messageReceiver, @Nonnull LanguageFileField field, Function builder){ + sendMessage(messageReceiver, field, defaultFeedbackType, builder); + } + + public void sendMessage(MessageReceiver messageReceiver, @Nonnull LanguageFileField field, FeedbackType feedbackType) { + sendMessage(messageReceiver, field, feedbackType, null); + } + + public void sendMessage(MessageReceiver messageReceiver, @Nonnull String content, FeedbackType feedbackType) { + sendMessage(messageReceiver, content, feedbackType, null); + } + + public void sendMessage(MessageReceiver messageReceiver, @Nonnull LanguageFileField field, FeedbackType feedbackType, Function builder){ + String content = get(field); + sendMessage(messageReceiver, content, feedbackType, builder); + } + + public void sendMessage(MessageReceiver messageReceiver, @Nonnull String content, FeedbackType feedbackType, Function builder){ + String prefix = getChatFeedbackColor(feedbackType) + get(LanguageFileField.CHAT_FEEDBACK_PREFIX); + sendMessage(messageReceiver, prefix, content, builder); + } + + public void sendMessage(CommandSender commandSender, @Nonnull String content){ + sendMessage(new SimpleMessageReceiver(commandSender), content); + } + + public void sendMessage(CommandSender commandSender, @Nonnull LanguageFileField field){ + sendMessage(new SimpleMessageReceiver(commandSender), field); + } + + public void sendMessage(CommandSender commandSender, @Nonnull LanguageFileField field, FeedbackType feedbackType){ + sendMessage(new SimpleMessageReceiver(commandSender), field, feedbackType, null); + } + + public void sendMessage(CommandSender commandSender, @Nonnull LanguageFileField field, Function builder){ + sendMessage(new SimpleMessageReceiver(commandSender), field, defaultFeedbackType, builder); + } + + public void sendMultilineMessage(CommandSender commandSender, @Nonnull LanguageFileField field){ + sendMultilineMessage(new SimpleMessageReceiver(commandSender), field); + } + + public void sendMultilineMessage(CommandSender commandSender, @Nonnull LanguageFileField field, Function builder){ + sendMultilineMessage(new SimpleMessageReceiver(commandSender), get(field), defaultFeedbackType, builder); + } + + public void sendMultilineMessage(CommandSender commandSender, @Nonnull String content){ + sendMultilineMessage(new SimpleMessageReceiver(commandSender), content); + } + + public void sendMultilineMessage(CommandSender commandSender, @Nonnull String content, Function builder){ + sendMultilineMessage(new SimpleMessageReceiver(commandSender), content, defaultFeedbackType, builder); + } + + public void sendMultilineMessage(MessageReceiver messageReceiver, @Nonnull LanguageFileField field){ + sendMultilineMessage(messageReceiver, field, defaultFeedbackType); + } + + public void sendMultilineMessage(MessageReceiver messageReceiver, @Nonnull LanguageFileField field, FeedbackType feedbackType){ + sendMultilineMessage(messageReceiver, get(field), feedbackType, null); + } + + public void sendMultilineMessage(MessageReceiver messageReceiver, @Nonnull LanguageFileField field, Function builder){ + sendMultilineMessage(messageReceiver, get(field), defaultFeedbackType, builder); + } + + public void sendMultilineMessage(MessageReceiver messageReceiver, @Nonnull String content){ + sendMultilineMessage(messageReceiver, content, defaultFeedbackType); + } + + public void sendMultilineMessage(MessageReceiver messageReceiver, @Nonnull String content, FeedbackType feedbackType){ + sendMultilineMessage(messageReceiver, content, feedbackType, null); + } + + public void sendMultilineMessage(MessageReceiver messageReceiver, @Nonnull String content, FeedbackType feedbackType, Function builder){ + String prefix = getChatFeedbackColor(feedbackType); + sendMessage(messageReceiver, prefix, content, builder); + } + + public void sendMultilineMessage(JRidesPlayer apiPlayer, @Nonnull LanguageFileField field, Function builder){ + if(!(apiPlayer instanceof MessageReceiver)){ + throw new RuntimeException("Unexpected type in JRidesPlayer at languagefile"); + } + + sendMultilineMessage((MessageReceiver) apiPlayer, get(field), defaultFeedbackType, builder); + } + + public void sendMessage(MessageReceiver messageReceiver, String prefix, @Nonnull String content, Function builderFunction){ + if(content.equals("")) return; + + StringReplacementBuilder builder = new StringReplacementBuilder(); + if(builderFunction != null) builder = builderFunction.apply(builder); + + content = builder.apply(content); + + messageReceiver.sendMessage(ChatColor.translateAlternateColorCodes('&', prefix + content)); + } + + private String getChatFeedbackColor(FeedbackType feedbackType){ + String chatFeedbackColor; + if(feedbackType.equals(FeedbackType.INFO)) chatFeedbackColor = get(LanguageFileField.CHAT_FEEDBACK_INFO_COLOR); + else if(feedbackType.equals(FeedbackType.WARNING)) chatFeedbackColor = get(LanguageFileField.CHAT_FEEDBACK_WARNING_COLOR); + else if(feedbackType.equals(FeedbackType.SEVERE)) chatFeedbackColor = get(LanguageFileField.CHAT_FEEDBACK_SEVERE_COLOR); + else if(feedbackType.equals(FeedbackType.CONFLICT)) chatFeedbackColor = get(LanguageFileField.CHAT_FEEDBACK_WARNING_COLOR); + else throw new RuntimeException("Unsupported feedback type"); + + return chatFeedbackColor; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/language/LanguageFileField.java b/src/main/java/com/jverbruggen/jrides/language/LanguageFileField.java new file mode 100644 index 00000000..7581a04d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/language/LanguageFileField.java @@ -0,0 +1,71 @@ +package com.jverbruggen.jrides.language; + +public enum LanguageFileField { + CHAT_FEEDBACK_PREFIX, + CHAT_FEEDBACK_INFO_COLOR, + CHAT_FEEDBACK_WARNING_COLOR, + CHAT_FEEDBACK_SEVERE_COLOR, + + COMMAND_RIDE_DISPATCHED_MESSAGE, + + COMMAND_VISUALIZE_ADDED_VIEWER, + COMMAND_VISUALIZE_REMOVED_VIEWER, + + NOTIFICATION_PLUGIN_STILL_LOADING, + + NOTIFICATION_RIDE_CONTROL_ACTIVE, + NOTIFICATION_RIDE_CONTROL_INACTIVE, + + NOTIFICATION_RIDE_DISPATCH_PROBLEMS, + NOTIFICATION_RIDE_NO_TRAIN_PRESENT, + NOTIFICATION_RIDE_NEXT_BLOCK_OCCUPIED, + NOTIFICATION_RIDE_WAITING_TIME, + NOTIFICATION_RIDE_RESTRAINTS_NOT_CLOSED, + NOTIFICATION_RIDE_GATES_NOT_CLOSED, + NOTIFICATION_RIDE_GATE_NOT_CLOSED, + + NOTIFICATION_RIDE_COUNTER_UPDATE, + NOTIFICATION_RIDE_STATE_OPEN, + NOTIFICATION_RIDE_STATE_CLOSED, + + NOTIFICATION_SHIFT_EXIT_CONFIRMATION, + NOTIFICATION_SHIFT_EXIT_CONFIRMED, + NOTIFICATION_DISPATCH_WAIT_GENERIC, + NOTIFICATION_DISPATCH_WAIT_SPECIFIC, + NOTIFICATION_RESTRAINT_ON_EXIT_ATTEMPT, + NOTIFICATION_RESTRAINT_ON_ENTER_ATTEMPT, + NOTIFICATION_RESTRAINT_ENTER_OVERRIDE, + NOTIFICATION_CANNOT_ENTER_RIDE, + NOTIFICATION_CANNOT_ENTER_RIDE_CLOSED, + + NOTIFICATION_OPERATOR_IDLE_TOO_LONG, + NOTIFICATION_WARPED, + + ELEVATED_OPERATOR_OVERRIDE_VICTIM_MESSAGE, + + ERROR_SMOOTH_COASTERS_DISABLED, + ERROR_GENERAL_NO_PERMISSION_MESSAGE, + ERROR_PLAYER_COMMAND_ONLY_MESSAGE, + ERROR_UNKNOWN_COMMAND_MESSAGE, + ERROR_OPERATING_CABIN_OCCUPIED, + ERROR_OPERATING_NO_PERMISSION, + ERROR_RIDE_CONTROL_MENU_NOT_FOUND, + ERROR_RIDE_OVERVIEW_MAP_NOT_FOUND, + + MENU_RIDE_OVERVIEW_TITLE, + MENU_RIDE_OVERVIEW_STATUS_OPEN, + MENU_RIDE_OVERVIEW_STATUS_CLOSED, + MENU_RIDE_OVERVIEW_STATUS_MAINTENANCE, + MENU_RIDE_CONTROL_TITLE, + MENU_ADMIN_RIDE_CONTROL_TITLE, + + BUTTON_CLAIM_CABIN, + BUTTON_CABIN_CLAIMED, + BUTTON_DISPATCH_STATE, + BUTTON_DISPATCH_PROBLEM_STATE, + BUTTON_PROBLEMS_STATE, + BUTTON_GATES_OPEN_STATE, + BUTTON_GATES_CLOSED_STATE, + BUTTON_RESTRAINTS_OPEN_STATE, + BUTTON_RESTRAINTS_CLOSED_STATE +} diff --git a/src/main/java/com/jverbruggen/jrides/language/LanguageFileTag.java b/src/main/java/com/jverbruggen/jrides/language/LanguageFileTag.java new file mode 100644 index 00000000..686a97c6 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/language/LanguageFileTag.java @@ -0,0 +1,10 @@ +package com.jverbruggen.jrides.language; + +public class LanguageFileTag { + public static final String name = "NAME"; + public static final String rideIdentifier = "RIDE_IDENTIFIER"; + public static final String rideDisplayName = "RIDE_DISPLAY_NAME"; + public static final String player = "PLAYER"; + public static final String time = "TIME"; + public static final String rideCount = "RIDE_COUNT"; +} diff --git a/src/main/java/com/jverbruggen/jrides/language/StringReplacementBuilder.java b/src/main/java/com/jverbruggen/jrides/language/StringReplacementBuilder.java new file mode 100644 index 00000000..a27db6f2 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/language/StringReplacementBuilder.java @@ -0,0 +1,37 @@ +package com.jverbruggen.jrides.language; + +import java.util.HashMap; +import java.util.Map; + +import javax.annotation.Nonnull; + +public class StringReplacementBuilder { + private final Map replacements; + + public StringReplacementBuilder() { + this.replacements = new HashMap<>(); + } + + public StringReplacementBuilder add(String tag, String replacement){ + replacements.put(tag, replacement); + return this; + } + + public Map collect(){ + return replacements; + } + + public @Nonnull String apply(@Nonnull String input){ + String output = input; + + if(replacements.size() > 0){ + for(Map.Entry replacement : replacements.entrySet()){ + String tag = replacement.getKey(); + output = output.replace("%" + tag + "%", replacement.getValue()); + } + } + + if(output == null) throw new RuntimeException("Unexpected output = null when applying input on StringReplacementBuilder"); + return output; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/listener/PlayerTeleportToRideListener.java b/src/main/java/com/jverbruggen/jrides/listener/PlayerTeleportToRideListener.java new file mode 100644 index 00000000..e28fe9d6 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/listener/PlayerTeleportToRideListener.java @@ -0,0 +1,25 @@ +package com.jverbruggen.jrides.listener; + +import com.jverbruggen.jrides.api.JRidesPlayerLocation; +import com.jverbruggen.jrides.event.player.PlayerTeleportByJRidesEvent; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; + +public class PlayerTeleportToRideListener implements Listener { + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerTeleportToRide(PlayerTeleportByJRidesEvent e){ + if(!e.isCancelled() || e.isHardTeleport()){ + Player bukkitPlayer = e.getPlayer().getBukkitPlayer(); + JRidesPlayerLocation playerLocation = e.getLocation(); + bukkitPlayer.teleport(new Location(bukkitPlayer.getWorld(), + playerLocation.getX(), + playerLocation.getY(), + playerLocation.getZ(), + (float) playerLocation.getYaw(), + (float) playerLocation.getPitch())); + } + } +} diff --git a/src/main/java/com/jverbruggen/jrides/logging/JRidesLogger.java b/src/main/java/com/jverbruggen/jrides/logging/JRidesLogger.java new file mode 100644 index 00000000..83ef0549 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/logging/JRidesLogger.java @@ -0,0 +1,78 @@ +package com.jverbruggen.jrides.logging; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class JRidesLogger extends Logger { + private final Logger bukkitPluginLogger; + private Level threshold; + private boolean broadcastMode; + private List enabledLogTypes; + private boolean bukkitActive; + + public JRidesLogger(Logger bukkitPluginLogger, boolean broadcastMode, boolean bukkitActive) { + super("JRidesLogger", null); + this.bukkitPluginLogger = bukkitPluginLogger; + this.threshold = Level.INFO; + this.broadcastMode = broadcastMode; + this.enabledLogTypes = new ArrayList<>(); + this.bukkitActive = bukkitActive; + + enableLogType(LogType.CRASH); +// enableLogType(LogType.SECTIONS); +// enableLogType(LogType.SECTIONS_DETAIL); + } + + public void enableLogType(LogType logType){ + enabledLogTypes.add(logType); + } + + public void info(LogType logType, String msg){ + if(enabledLogTypes.contains(logType)) log(Level.INFO, msg); + } + + public void warning(LogType logType, String msg){ + if(enabledLogTypes.contains(logType)) log(Level.WARNING, msg); + } + + public void severe(LogType logType, String msg){ + if(enabledLogTypes.contains(logType)) log(Level.SEVERE, msg); + } + + /** + * Only to be used temporarily + */ + public void debug(String msg) { + if(bukkitActive){ + Bukkit.broadcastMessage(msg); + }else{ + System.out.println(msg); + } + } + + @Override + public void log(Level level, String msg) { + if(level.intValue() < threshold.intValue()) return; + + if(broadcastMode) { + ChatColor color; + if(level.equals(Level.INFO)) + color = ChatColor.GRAY; + else if(level.equals(Level.WARNING)) + color = ChatColor.YELLOW; + else if(level.equals(Level.SEVERE)) + color = ChatColor.DARK_RED; + else + color = ChatColor.GRAY; + + Bukkit.broadcastMessage(color + "[jrides] " + msg); + } else + bukkitPluginLogger.log(level, msg); + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/logging/LogType.java b/src/main/java/com/jverbruggen/jrides/logging/LogType.java new file mode 100644 index 00000000..cf063573 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/logging/LogType.java @@ -0,0 +1,24 @@ +package com.jverbruggen.jrides.logging; + +public class LogType { + private final String name; + + public LogType(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + @Override + public boolean equals(Object obj) { + return (obj instanceof LogType) + && ((LogType) obj).getName().equalsIgnoreCase(getName()); + } + + public static final LogType SECTIONS = new LogType("SECTIONS"); + public static final LogType SECTIONS_DETAIL = new LogType("SECTIONS_DETAIL"); + public static final LogType CRASH = new LogType("CRASH"); + public static final LogType PACKET = new LogType("PACKET"); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/BaseVirtualEntity.java b/src/main/java/com/jverbruggen/jrides/models/entity/BaseVirtualEntity.java new file mode 100644 index 00000000..507d9dd5 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/BaseVirtualEntity.java @@ -0,0 +1,275 @@ +package com.jverbruggen.jrides.models.entity; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.event.action.RideAction; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.ride.seat.Seat; +import com.jverbruggen.jrides.packets.PacketSender; +import com.jverbruggen.jrides.state.viewport.ViewportManager; +import org.bukkit.Bukkit; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public abstract class BaseVirtualEntity implements VirtualEntity { + protected PacketSender packetSender; + protected ViewportManager viewportManager; + + private Player passenger; + private boolean allowsPassengerValue; + private boolean passengerSyncCounterActive; + private int passengerSyncCounter; + private Seat partOfSeat; + private String customName; + + protected boolean spawned; + protected boolean rendered; + protected UUID uuid; + protected final int entityId; + protected Vector3 location; + protected List viewers; + + private int teleportSyncCountdownState; // If entity isn't teleported every few frames, it starts drifting due to only relative updates + + private RideAction customAction; + private RideHandle belongsToRideHandle; + + public BaseVirtualEntity(PacketSender packetSender, ViewportManager viewportManager, Vector3 location, int entityId) { + this.passenger = null; + this.allowsPassengerValue = false; + this.passengerSyncCounterActive = false; + this.passengerSyncCounter = 0; + this.partOfSeat = null; + this.customName = null; + + this.packetSender = packetSender; + this.viewportManager = viewportManager; + this.entityId = entityId; + this.uuid = UUID.randomUUID(); + this.location = location; + this.viewers = new ArrayList<>(); + this.spawned = true; + this.rendered = true; + this.teleportSyncCountdownState = 0; + this.customAction = null; + this.belongsToRideHandle = null; + } + + @Override + public Player getPassenger() { + return passenger; + } + + @Override + public boolean allowsPassenger() { + return allowsPassengerValue; + } + + @Override + public boolean hasPassenger() { + return passenger != null; + } + + @Override + public void setPassenger(Player player) { + this.passenger = player; + + packetSender.sendMountVirtualEntityPacket(viewers, player, entityId); + + if(player != null){ + this.passengerSyncCounterActive = true; + this.passengerSyncCounter = 0; + }else{ + this.passengerSyncCounterActive = false; + } + } + + @Override + public void setHostSeat(Seat seat) { + partOfSeat = seat; + this.allowsPassengerValue = true; + } + + @Override + public Seat getHostSeat() { + return partOfSeat; + } + + @Override + public List getViewers() { + return viewers; + } + + @Override + public void addViewer(Player player) { + if(viewers.contains(player)) return; + + viewers.add(player); + } + + @Override + public void removeViewer(Player player) { + viewers.remove(player); + } + + @Override + public boolean isViewer(Player player) { + return viewers.contains(player); + } + + @Override + public Vector3 getLocation() { + return location; + } + + @Override + public void setLocation(Vector3 newLocation) { + if(newLocation == null) return; + + final int chunkSize = viewportManager.getRenderChunkSize(); + + if(Vector3.chunkRotated(location, newLocation, chunkSize)){ + viewportManager.updateForEntity(this); + } + + double distanceSquared = newLocation.distanceSquared(this.location); + + if(distanceSquared > 49 || teleportSyncCountdownState > 60) { + Vector3 blockLocation = newLocation.toBlock(); + teleportEntity(blockLocation); + teleportSyncCountdownState = 0; + + Vector3 delta = Vector3.subtract(newLocation, newLocation.toBlock()); + moveEntity(delta, 0); + } + else{ + Vector3 delta = Vector3.subtract(newLocation, this.location); + moveEntity(delta, 0); + } + + this.location = newLocation; + + teleportSyncCountdownState++; + } + + @Override + public void setRotation(Quaternion orientation) { + if(orientation == null) return; + double packetYaw = orientation.getPacketYaw(); + + moveEntity(Vector3.zero(), packetYaw); + } + + protected abstract void moveEntity(Vector3 delta, double yawRotation); + + protected abstract void teleportEntity(Vector3 newLocation); + + @Override + public String getUniqueIdentifier() { + return uuid.toString(); + } + + @Override + public UUID getUUID() { + return uuid; + } + + @Override + public int getEntityId() { + return entityId; + } + + @Override + public void despawn() { + spawned = false; + packetSender.destroyVirtualEntity(getViewers(), entityId); + } + + @Override + public void despawnFor(Player player, boolean unview) { + if(unview) + removeViewer(player); + + packetSender.destroyVirtualEntity(player, entityId); + } + + @Override + public void spawnForAll(List players, boolean hard) { + for(Player player : players){ + if(isViewer(player) && !hard) continue; + spawnFor(player); + } + } + + public void despawnForAll(List players, boolean unview){ + for(Player player : List.copyOf(players)){ + if(!isViewer(player)) continue; + despawnFor(player, unview); + } + } + + @Override + public boolean isAlive() { + return spawned; + } + + protected void syncPassenger(Vector3 position){ + if(passengerSyncCounterActive){ + if(passengerSyncCounter > 20){ + passengerSyncCounter = 0; + + this.passenger.setPositionWithoutTeleport(position); + }else passengerSyncCounter++; + } + } + + @Override + public void setCustomName(String customName) { + this.customName = customName; + + // TODO: Apply custom name packets + } + + @Override + public void setCustomAction(RideAction action) { + this.customAction = action; + } + + @Override + public boolean hasCustomAction() { + return this.customAction != null; + } + + @Override + public void runCustomAction(Player player) { + if(belongsToRideHandle == null){ + JRidesPlugin.getLogger().severe("Custom action failed because it doesnot belong to a ride handle"); + return; + } + this.customAction.accept(this, belongsToRideHandle, player); + } + + @Override + public void setBelongsToRide(RideHandle rideHandle) { + belongsToRideHandle = rideHandle; + } + + @Override + public void setRendered(boolean render) { + if(render && !rendered){ + rendered = true; + spawnForAll(getViewers(), true); + }else if(!render && rendered){ + rendered = false; + despawnForAll(getViewers(), false); + } + } + + @Override + public boolean isRendered() { + return rendered; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/BroadcastMessageReceiver.java b/src/main/java/com/jverbruggen/jrides/models/entity/BroadcastMessageReceiver.java new file mode 100644 index 00000000..dc68cc10 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/BroadcastMessageReceiver.java @@ -0,0 +1,10 @@ +package com.jverbruggen.jrides.models.entity; + +import org.bukkit.Bukkit; + +public class BroadcastMessageReceiver implements MessageReceiver { + @Override + public void sendMessage(String message) { + Bukkit.broadcastMessage(message); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/EntityIdFactory.java b/src/main/java/com/jverbruggen/jrides/models/entity/EntityIdFactory.java new file mode 100644 index 00000000..8680ccc6 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/EntityIdFactory.java @@ -0,0 +1,26 @@ +package com.jverbruggen.jrides.models.entity; + +/** + * Creates random entity id in range from a - b + */ +public class EntityIdFactory { + private final int upper; + private int next; + + public EntityIdFactory(int lower, int upper) { + this.upper = upper; + this.next = lower; + } + + private int next(){ + int val = this.next++; + if(val > upper){ + throw new IllegalStateException("Entity ID factory overflowing, restart the server!"); + } + return val; + } + + public int newId(){ + return next(); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/MessageReceiver.java b/src/main/java/com/jverbruggen/jrides/models/entity/MessageReceiver.java new file mode 100644 index 00000000..f116d922 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/MessageReceiver.java @@ -0,0 +1,5 @@ +package com.jverbruggen.jrides.models.entity; + +public interface MessageReceiver { + void sendMessage(String message); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/Player.java b/src/main/java/com/jverbruggen/jrides/models/entity/Player.java new file mode 100644 index 00000000..b497b0d8 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/Player.java @@ -0,0 +1,241 @@ +package com.jverbruggen.jrides.models.entity; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.smoothanimation.SmoothAnimationSupport; +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.control.controller.RideController; +import com.jverbruggen.jrides.event.player.PlayerTeleportByJRidesEvent; +import com.jverbruggen.jrides.language.FeedbackType; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.language.LanguageFileTag; +import com.jverbruggen.jrides.models.entity.agent.MessageAgent; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.ride.seat.Seat; +import com.jverbruggen.jrides.models.ride.count.RideCounterRecordCollection; +import com.jverbruggen.jrides.nms.NMSHandler; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.player.PlayerManager; +import net.md_5.bungee.api.ChatMessageType; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Location; +import org.bukkit.Sound; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public class Player implements MessageAgent, JRidesPlayer { + private final org.bukkit.entity.Player bukkitPlayer; + private SeatedOnContext seatedOnContext; + private SmoothAnimationSupport smoothAnimationSupport; + private final LanguageFile languageFile; + private RideController operating; + private final List viewing; + private final RideCounterRecordCollection rideCounters; + + public Player(org.bukkit.entity.Player bukkitPlayer, RideCounterRecordCollection rideCounters) { + this.bukkitPlayer = bukkitPlayer; + this.seatedOnContext = null; + this.smoothAnimationSupport = SmoothAnimationSupport.UNKNOWN; + this.languageFile = ServiceProvider.getSingleton(LanguageFile.class); + this.operating = null; + this.viewing = new ArrayList<>(); + this.rideCounters = rideCounters; + } + + public RideCounterRecordCollection getRideCounters() { + return rideCounters; + } + + public Vector3 getLocation(){ + Location location = bukkitPlayer.getLocation(); + + double x = location.getX(); + double y = location.getY(); + double z = location.getZ(); + + return new Vector3(x, y, z); + } + + @Override + public void sendMessage(String message){ + if(message.equals("")) return; + bukkitPlayer.sendMessage(message); + } + + public void sendActionbarMessage(String message){ + bukkitPlayer.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(message)); + } + + public void sendTitle(String title, String subtitle, int stay){ + bukkitPlayer.sendTitle(title, subtitle, 10, stay, 10); + } + + public org.bukkit.entity.Player getBukkitPlayer(){ + return bukkitPlayer; + } + + public UUID getUniqueId(){ + return bukkitPlayer.getUniqueId(); + } + + public Seat getSeatedOn(){ + if(!isSeated()) return null; + return this.seatedOnContext.getSeat(); + } + + public void setSeatedOnContext(SeatedOnContext seatedOnContext) { + this.seatedOnContext = seatedOnContext; + } + + public SeatedOnContext getSeatedOnContext() { + return seatedOnContext; + } + + public boolean isSeated(){ + return this.seatedOnContext != null; + } + + public void setPositionWithoutTeleport(Vector3 position){ +// JRidesPlugin.getPacketSender().sendClientPositionPacket(this, position); + ServiceProvider.getSingleton(NMSHandler.class).setPlayerLocationNoTeleport(this, position); + } + + public boolean shouldResetSmoothAnimationSupport(){ + return smoothAnimationSupport.equals(SmoothAnimationSupport.UNKNOWN); + } + + public boolean hasSmoothAnimationSupport() { + return smoothAnimationSupport.equals(SmoothAnimationSupport.AVAILABLE); + } + + public void setSmoothAnimationSupport(boolean smoothAnimationSupport) { + if(this.smoothAnimationSupport != SmoothAnimationSupport.UNKNOWN) return; // Cannot reset smooth animation without rejoin + + this.smoothAnimationSupport = (smoothAnimationSupport ? SmoothAnimationSupport.AVAILABLE : SmoothAnimationSupport.UNAVAILABLE); + if(!smoothAnimationSupport){ + languageFile.sendMessage(bukkitPlayer, LanguageFileField.ERROR_SMOOTH_COASTERS_DISABLED, FeedbackType.WARNING); + } + } + + public void clearSmoothAnimationRotation(){ + if(!hasSmoothAnimationSupport()) return; + JRidesPlugin.getSmoothAnimation().clearRotation(this); + } + + public void setSmoothAnimationRotation(Quaternion orientation){ + if(!hasSmoothAnimationSupport()) return; + JRidesPlugin.getSmoothAnimation().setRotation(this, orientation); + } + + public String getName() { + return bukkitPlayer.getName(); + } + + public String getIdentifier(){ + return bukkitPlayer.getUniqueId().toString(); + } + + public boolean equals(Player other) { + if(other == null) return false; + return this.getBukkitPlayer().getUniqueId().equals(other.getBukkitPlayer().getUniqueId()); + } + + public boolean setOperating(RideController rideController) { + if(rideController != null && rideController.getOperator() == this && operating == rideController) return true; + + if(operating != null){ + languageFile.sendMessage(this, LanguageFileField.NOTIFICATION_RIDE_CONTROL_INACTIVE, + (b) -> b.add(LanguageFileTag.rideDisplayName, operating.getRide().getDisplayName())); + operating.setOperator(null); + operating = null; + } + + if(rideController == null) return true; + + if(!hasPermission(Permissions.CABIN_OPERATE)){ + languageFile.sendMessage(this, LanguageFileField.ERROR_OPERATING_NO_PERMISSION); + return false; + } + + boolean set = rideController.setOperator(this); + if(!set){ + languageFile.sendMessage(this, LanguageFileField.ERROR_OPERATING_CABIN_OCCUPIED); + bukkitPlayer.closeInventory(); + return false; + } + + operating = rideController; + + languageFile.sendMessage(this, LanguageFileField.NOTIFICATION_RIDE_CONTROL_ACTIVE, + builder -> builder.add(LanguageFileTag.rideDisplayName, operating.getRide().getDisplayName())); + return true; + } + + public void clearOperating(){ + operating = null; + } + + public RideController getOperating(){ + return operating; + } + + public void addViewing(VirtualEntity virtualEntity){ + if(isViewing(virtualEntity)) return; + viewing.add(virtualEntity); + } + + public void removeViewing(VirtualEntity virtualEntity){ + viewing.remove(virtualEntity); + } + + public boolean isViewing(VirtualEntity virtualEntity){ + return viewing.contains(virtualEntity); + } + + public List getViewing() { + return viewing; + } + + public void teleport(PlayerLocation location){ + teleport(location, false); + } + + public void teleport(PlayerLocation location, boolean hard) { + if(hard) + getBukkitPlayer().teleport(location.toBukkitLocation(getBukkitPlayer().getWorld())); + else + PlayerTeleportByJRidesEvent.sendEvent(this, location, true); + } + + public void teleport(Vector3 location, double yaw){ + PlayerLocation playerLocation = PlayerLocation.fromVector3(location); + playerLocation.setYaw(yaw); + + teleport(playerLocation, false); + } + + public boolean hasPermission(String permission){ + return bukkitPlayer.hasPermission(permission); + } + + @Override + public boolean isPlayer() { + return true; + } + + @Override + public Player getPlayer(PlayerManager playerManager) { + return this; + } + + public void playSound(Sound sound){ + if(sound == null) return; + bukkitPlayer.playSound(bukkitPlayer.getLocation(), sound, 1, 1); + } +} + diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/SeatedOnContext.java b/src/main/java/com/jverbruggen/jrides/models/entity/SeatedOnContext.java new file mode 100644 index 00000000..0a4b0d78 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/SeatedOnContext.java @@ -0,0 +1,66 @@ +package com.jverbruggen.jrides.models.entity; + +import com.jverbruggen.jrides.common.Sync; +import com.jverbruggen.jrides.models.ride.seat.Seat; + +enum SeatedOnState { + CREATED, + SETUP, + RESTORED +} + +public class SeatedOnContext { + private SeatedOnState state; + private final Seat seat; + private final boolean wasFlying; + private final boolean wasAllowedFlying; + + public SeatedOnContext(Seat seat, boolean wasFlying, boolean wasAllowedFlying) { + this.state = SeatedOnState.CREATED; + this.seat = seat; + this.wasFlying = wasFlying; + this.wasAllowedFlying = wasAllowedFlying; + } + + public static SeatedOnContext create(Seat seat, Player player){ + org.bukkit.entity.Player bukkitPlayer = player.getBukkitPlayer(); + boolean wasFlying = bukkitPlayer.isFlying(); + boolean wasAllowedFlying = bukkitPlayer.getAllowFlight(); + + return new SeatedOnContext(seat, wasFlying, wasAllowedFlying); + } + + public void setup(Player player){ + if(state != SeatedOnState.CREATED) throw new RuntimeException("Already set up context"); + + org.bukkit.entity.Player bukkitPlayer = player.getBukkitPlayer(); + + Sync.runSynced(() -> { + bukkitPlayer.setFlying(true); + bukkitPlayer.setAllowFlight(true); + + player.setSeatedOnContext(this); + state = SeatedOnState.SETUP; + }); + } + + public void restore(Player player){ + if(state != SeatedOnState.SETUP) throw new RuntimeException("Already restored context"); + + org.bukkit.entity.Player bukkitPlayer = player.getBukkitPlayer(); + + Sync.runSynced(() -> { + bukkitPlayer.setFlying(wasFlying); + bukkitPlayer.setAllowFlight(wasAllowedFlying); + + player.clearSmoothAnimationRotation(); + + player.setSeatedOnContext(null); + state = SeatedOnState.RESTORED; + }); + } + + public Seat getSeat() { + return seat; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/SimpleMessageReceiver.java b/src/main/java/com/jverbruggen/jrides/models/entity/SimpleMessageReceiver.java new file mode 100644 index 00000000..85928cf6 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/SimpleMessageReceiver.java @@ -0,0 +1,20 @@ +package com.jverbruggen.jrides.models.entity; + +import org.bukkit.command.CommandSender; + +public class SimpleMessageReceiver implements MessageReceiver { + private final CommandSender commandSender; + + public SimpleMessageReceiver(CommandSender commandSender) { + this.commandSender = commandSender; + } + + @Override + public void sendMessage(String message) { + commandSender.sendMessage(message); + } + + public static SimpleMessageReceiver from(CommandSender commandSender){ + return new SimpleMessageReceiver(commandSender); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/TrainModelItem.java b/src/main/java/com/jverbruggen/jrides/models/entity/TrainModelItem.java new file mode 100644 index 00000000..f49a352f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/TrainModelItem.java @@ -0,0 +1,15 @@ +package com.jverbruggen.jrides.models.entity; + +import org.bukkit.inventory.ItemStack; + +public class TrainModelItem { + private final ItemStack model; + + public TrainModelItem(ItemStack model) { + this.model = model; + } + + public ItemStack getItemStack() { + return model; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/VirtualBukkitEntity.java b/src/main/java/com/jverbruggen/jrides/models/entity/VirtualBukkitEntity.java new file mode 100644 index 00000000..74ae6127 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/VirtualBukkitEntity.java @@ -0,0 +1,75 @@ +package com.jverbruggen.jrides.models.entity; + +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.packets.PacketSender; +import com.jverbruggen.jrides.state.viewport.ViewportManager; +import org.bukkit.entity.EntityType; + +public class VirtualBukkitEntity extends BaseVirtualEntity { + private final EntityType entityType; + + private double yawRotation; + private final int leashedToEntity; + + public VirtualBukkitEntity(PacketSender packetSender, ViewportManager viewportManager, Vector3 location, EntityType entityType, double yawRotation, int entityId) { + super(packetSender, viewportManager, location, entityId); + this.entityType = entityType; + this.yawRotation = yawRotation; + this.leashedToEntity = -1; + } + + @Override + protected void moveEntity(Vector3 delta, double yawRotation) { + packetSender.moveVirtualEntity(this.getViewers(), entityId, delta, yawRotation); + } + + @Override + protected void teleportEntity(Vector3 newLocation) { + packetSender.teleportVirtualEntity(this.getViewers(), entityId, newLocation); + } + + @Override + public Quaternion getRotation() { + return Quaternion.fromYawPitchRoll(0, yawRotation, 0); + } + + @Override + public double getYaw() { + return yawRotation; + } + + @Override + public void spawnFor(Player player) { + addViewer(player); + if(!rendered) return; + + packetSender.spawnVirtualEntity(player, entityId, location, getYaw(), entityType, false, leashedToEntity); + } + + @Override + public boolean shouldRenderFor(Player player) { + return false; + } + + @Override + public void setModel(TrainModelItem model) { + throw new RuntimeException("Not implemented"); + } + + @Override + public void setLocation(Vector3 newLocation) { + super.setLocation(newLocation); + if(newLocation == null) return; + + syncPassenger(newLocation); + } + + @Override + public void setRotation(Quaternion orientation) { + super.setRotation(orientation); + + if(orientation != null) + this.yawRotation = orientation.getYaw() - 90; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/VirtualEntity.java b/src/main/java/com/jverbruggen/jrides/models/entity/VirtualEntity.java new file mode 100644 index 00000000..9c96776a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/VirtualEntity.java @@ -0,0 +1,49 @@ +package com.jverbruggen.jrides.models.entity; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.event.action.RideAction; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.ride.seat.Seat; + +import java.util.List; +import java.util.UUID; + +public interface VirtualEntity { + String getUniqueIdentifier(); + UUID getUUID(); + int getEntityId(); + + Player getPassenger(); + boolean allowsPassenger(); + boolean hasPassenger(); + void setPassenger(Player player); + + Vector3 getLocation(); + Quaternion getRotation(); + + double getYaw(); + void setLocation(Vector3 location); + void setRotation(Quaternion orientation); + List getViewers(); + void addViewer(Player player); + void removeViewer(Player player); + boolean isViewer(Player player); + void spawnFor(Player player); + void spawnForAll(List players, boolean hard); + void despawnFor(Player player, boolean unview); + void despawn(); + boolean shouldRenderFor(Player player); + boolean isAlive(); + void setHostSeat(Seat seat); + Seat getHostSeat(); + void setModel(TrainModelItem model); + void setCustomName(String name); + void setCustomAction(RideAction rideAction); + boolean hasCustomAction(); + void runCustomAction(Player player); + void setBelongsToRide(RideHandle rideHandle); + + void setRendered(boolean render); + boolean isRendered(); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/VirtualFallingBlock.java b/src/main/java/com/jverbruggen/jrides/models/entity/VirtualFallingBlock.java new file mode 100644 index 00000000..eb64564d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/VirtualFallingBlock.java @@ -0,0 +1,72 @@ +package com.jverbruggen.jrides.models.entity; + +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.packets.PacketSender; +import com.jverbruggen.jrides.state.viewport.ViewportManager; + +public class VirtualFallingBlock extends BaseVirtualEntity { + public VirtualFallingBlock(PacketSender packetSender, ViewportManager viewportManager, Vector3 location, int entityId) { + super(packetSender, viewportManager, location, entityId); + } + + @Override + protected void moveEntity(Vector3 delta, double yawRotation) { + + } + + @Override + protected void teleportEntity(Vector3 newLocation) { + + } + + @Override + public Player getPassenger() { + return null; + } + + @Override + public boolean allowsPassenger() { + return false; + } + + @Override + public boolean hasPassenger() { + return false; + } + + @Override + public void setPassenger(Player player) { + return; + } + + @Override + public Quaternion getRotation() { + return new Quaternion(); + } + + @Override + public double getYaw() { + return 0; + } + + @Override + public void spawnFor(Player player) { + addViewer(player); + + if(!rendered) + return; + + return; + } + + @Override + public boolean shouldRenderFor(Player player) { + return false; + } + + @Override + public void setModel(TrainModelItem model) { + throw new RuntimeException("Not implemented"); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/agent/CommandSenderMessageAgent.java b/src/main/java/com/jverbruggen/jrides/models/entity/agent/CommandSenderMessageAgent.java new file mode 100644 index 00000000..ca33f2f8 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/agent/CommandSenderMessageAgent.java @@ -0,0 +1,34 @@ +package com.jverbruggen.jrides.models.entity.agent; + +import com.jverbruggen.jrides.state.player.PlayerManager; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class CommandSenderMessageAgent implements MessageAgent { + private CommandSender commandSender; + + public CommandSenderMessageAgent(CommandSender commandSender) { + this.commandSender = commandSender; + } + + @Override + public boolean hasPermission(String permission) { + if(permission == null) return true; + return commandSender.hasPermission(permission); + } + + @Override + public boolean isPlayer() { + return commandSender instanceof Player; + } + + @Override + public com.jverbruggen.jrides.models.entity.Player getPlayer(PlayerManager playerManager) { + return playerManager.getPlayer((Player) commandSender); + } + + @Override + public void sendMessage(String message) { + commandSender.sendMessage(message); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/agent/MessageAgent.java b/src/main/java/com/jverbruggen/jrides/models/entity/agent/MessageAgent.java new file mode 100644 index 00000000..a585c392 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/agent/MessageAgent.java @@ -0,0 +1,11 @@ +package com.jverbruggen.jrides.models.entity.agent; + +import com.jverbruggen.jrides.models.entity.MessageReceiver; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.state.player.PlayerManager; + +public interface MessageAgent extends MessageReceiver { + boolean hasPermission(String permission); + boolean isPlayer(); + Player getPlayer(PlayerManager playerManager); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/agent/MessageAgentManager.java b/src/main/java/com/jverbruggen/jrides/models/entity/agent/MessageAgentManager.java new file mode 100644 index 00000000..40b35a0c --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/agent/MessageAgentManager.java @@ -0,0 +1,27 @@ +package com.jverbruggen.jrides.models.entity.agent; + +import org.bukkit.command.CommandSender; + +import java.util.HashMap; + +public class MessageAgentManager { + private final HashMap cache; + + public MessageAgentManager() { + this.cache = new HashMap<>(); + } + + public MessageAgent getOrCreateMessageAgent(CommandSender commandSender){ + MessageAgent existing = cache.get(commandSender.getName()); + if(existing != null) return existing; + + existing = new CommandSenderMessageAgent(commandSender); + cache.put(commandSender.getName(), existing); + return existing; + } + + public void removeMessageAgent(String name){ + cache.remove(name); + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/agent/MessageAgentManagerListener.java b/src/main/java/com/jverbruggen/jrides/models/entity/agent/MessageAgentManagerListener.java new file mode 100644 index 00000000..df38214a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/agent/MessageAgentManagerListener.java @@ -0,0 +1,19 @@ +package com.jverbruggen.jrides.models.entity.agent; + +import com.jverbruggen.jrides.event.player.PlayerQuitEvent; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class MessageAgentManagerListener implements Listener { + private final MessageAgentManager messageAgentManager; + + public MessageAgentManagerListener() { + this.messageAgentManager = ServiceProvider.getSingleton(MessageAgentManager.class); + } + + @EventHandler + public void onQuit(PlayerQuitEvent e){ + messageAgentManager.removeMessageAgent(e.getPlayer().getName()); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/armorstand/ArmorstandModels.java b/src/main/java/com/jverbruggen/jrides/models/entity/armorstand/ArmorstandModels.java new file mode 100644 index 00000000..11baae40 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/armorstand/ArmorstandModels.java @@ -0,0 +1,37 @@ +package com.jverbruggen.jrides.models.entity.armorstand; + +import com.jverbruggen.jrides.models.entity.TrainModelItem; + +public class ArmorstandModels { + private TrainModelItem head, mainHand, offHand; + + public ArmorstandModels() { + this.head = null; + this.mainHand = null; + this.offHand = null; + } + + public void setHead(TrainModelItem head) { + this.head = head; + } + public void setMainHand(TrainModelItem mainHand) { + this.mainHand = mainHand; + } + public void setOffHand(TrainModelItem offHand) { + this.offHand = offHand; + } + + public boolean hasHead() { return head != null; } + public boolean hasMainHand() { return mainHand != null; } + public boolean hasOffHand() { return offHand != null; } + + public TrainModelItem getHead() { + return head; + } + public TrainModelItem getMainHand() { + return mainHand; + } + public TrainModelItem getOffHand() { + return offHand; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/armorstand/ArmorstandRotations.java b/src/main/java/com/jverbruggen/jrides/models/entity/armorstand/ArmorstandRotations.java new file mode 100644 index 00000000..bac7d52b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/armorstand/ArmorstandRotations.java @@ -0,0 +1,64 @@ +package com.jverbruggen.jrides.models.entity.armorstand; + +import com.jverbruggen.jrides.models.math.Vector3; + +public class ArmorstandRotations { + private Vector3 head, body, offHand, mainHand, leftLeg, rightLeg; + + public ArmorstandRotations(){ + head = new Vector3(0,0,0); + body = new Vector3(0,0,0); + offHand = new Vector3(0,0,0); + mainHand = new Vector3(0,0,0); + leftLeg = new Vector3(0,0,0); + rightLeg = new Vector3(0,0,0); + } + + public Vector3 getHead() { + return head; + } + + public void setHead(Vector3 head) { + this.head = head; + } + + public Vector3 getBody() { + return body; + } + + public void setBody(Vector3 body) { + this.body = body; + } + + public Vector3 getOffHand() { + return offHand; + } + + public void setOffHand(Vector3 offHand) { + this.offHand = offHand; + } + + public Vector3 getMainHand() { + return mainHand; + } + + public void setMainHand(Vector3 mainHand) { + this.mainHand = mainHand; + } + + public Vector3 getLeftLeg() { + return leftLeg; + } + + public void setLeftLeg(Vector3 leftLeg) { + this.leftLeg = leftLeg; + } + + public Vector3 getRightLeg() { + return rightLeg; + } + + public void setRightLeg(Vector3 rightLeg) { + this.rightLeg = rightLeg; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/armorstand/VirtualArmorstand.java b/src/main/java/com/jverbruggen/jrides/models/entity/armorstand/VirtualArmorstand.java new file mode 100644 index 00000000..edf5e149 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/armorstand/VirtualArmorstand.java @@ -0,0 +1,114 @@ +package com.jverbruggen.jrides.models.entity.armorstand; + +import com.comphenix.protocol.wrappers.EnumWrappers; +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.models.entity.BaseVirtualEntity; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.TrainModelItem; +import com.jverbruggen.jrides.models.math.ArmorStandPose; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.packets.PacketSender; +import com.jverbruggen.jrides.packets.object.VirtualArmorstandConfiguration; +import com.jverbruggen.jrides.packets.packet.v1_19.ArmorstandRotationServerPacket; +import com.jverbruggen.jrides.state.viewport.ViewportManager; +import org.bukkit.Bukkit; + +import javax.annotation.Nonnull; +import java.util.List; + +public class VirtualArmorstand extends BaseVirtualEntity { + private static final Vector3 HEAD_OFFSET = new Vector3(0, 1.7, 0); + + private final Quaternion currentRotation; + private double yawRotation; + private final VirtualArmorstandConfiguration configuration; + + public VirtualArmorstand(PacketSender packetSender, ViewportManager viewportManager, Vector3 location, Quaternion rotation, double yawRotation, int entityId, @Nonnull VirtualArmorstandConfiguration configuration) { + super(packetSender, viewportManager, location, entityId); + + this.currentRotation = rotation; + this.yawRotation = yawRotation; + this.configuration = configuration; + } + + @Override + public Quaternion getRotation() { + return currentRotation; + } + + @Override + public double getYaw() { + return yawRotation; + } + + public void setYaw(double yawRotation){ + this.yawRotation = yawRotation; + } + + @Override + public void spawnFor(Player player) { + addViewer(player); + + if(!rendered) return; + + packetSender.spawnVirtualArmorstand(player, entityId, location, yawRotation, configuration); + + if(configuration.models().hasHead()){ + this.packetSender.sendApplyModelPacket(viewers, entityId, EnumWrappers.ItemSlot.HEAD, configuration.models().getHead()); + } + + setHeadPose(ArmorStandPose.getArmorStandPose(this.currentRotation)); + + if(getPassenger() != null){ + Bukkit.getScheduler().runTaskLater(JRidesPlugin.getBukkitPlugin(), + () -> packetSender.sendMountVirtualEntityPacket(List.of(player), getPassenger(), entityId), 1L); + } + } + + @Override + public boolean shouldRenderFor(Player player) { + return false; + } + + protected void setHeadPose(Vector3 rotation) { + configuration.rotations().setHead(rotation); + packetSender.sendRotationPacket(viewers, entityId, ArmorstandRotationServerPacket.Type.HEAD, rotation); + } + + public void setModel(TrainModelItem model){ + this.configuration.models().setHead(model); + this.packetSender.sendApplyModelPacket(viewers, entityId, EnumWrappers.ItemSlot.HEAD, model); + } + + @Override + public void setLocation(Vector3 newLocation) { + super.setLocation(newLocation); + + if(newLocation == null) return; + + syncPassenger(Vector3.add(newLocation, getHeadOffset())); + } + + @Override + public void setRotation(Quaternion orientation) { + if(orientation == null) return; + + currentRotation.copyFrom(orientation); + setHeadPose(ArmorStandPose.getArmorStandPose(orientation)); + } + + @Override + protected void moveEntity(Vector3 delta, double yawRotation) { + packetSender.moveVirtualArmorstand(this.getViewers(), entityId, delta, yawRotation); + } + + @Override + protected void teleportEntity(Vector3 newLocation) { + packetSender.teleportVirtualEntity(this.getViewers(), entityId, newLocation); + } + + public static Vector3 getHeadOffset(){ + return HEAD_OFFSET; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/armorstand/YawRotatedVirtualArmorstand.java b/src/main/java/com/jverbruggen/jrides/models/entity/armorstand/YawRotatedVirtualArmorstand.java new file mode 100644 index 00000000..0c538abf --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/armorstand/YawRotatedVirtualArmorstand.java @@ -0,0 +1,28 @@ +package com.jverbruggen.jrides.models.entity.armorstand; + +import com.jverbruggen.jrides.models.math.ArmorStandPose; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.packets.PacketSender; +import com.jverbruggen.jrides.packets.object.VirtualArmorstandConfiguration; +import com.jverbruggen.jrides.state.viewport.ViewportManager; + +import javax.annotation.Nonnull; + +public class YawRotatedVirtualArmorstand extends VirtualArmorstand { + public YawRotatedVirtualArmorstand(PacketSender packetSender, ViewportManager viewportManager, Vector3 location, Quaternion rotation, double yawRotation, int entityId, @Nonnull VirtualArmorstandConfiguration configuration) { + super(packetSender, viewportManager, location, rotation, yawRotation, entityId, configuration); + } + + @Override + public void setRotation(Quaternion orientation) { + if(orientation == null) return; + + Vector3 headPose = ArmorStandPose.getArmorStandPose(orientation); + headPose.y = 0; + + setHeadPose(headPose); + setYaw(orientation.getPacketYaw()); + moveEntity(Vector3.zero(), getYaw()); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/entity/listener/PassengerListener.java b/src/main/java/com/jverbruggen/jrides/models/entity/listener/PassengerListener.java new file mode 100644 index 00000000..c483b6d0 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/entity/listener/PassengerListener.java @@ -0,0 +1,36 @@ +package com.jverbruggen.jrides.models.entity.listener; + +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.player.PlayerManager; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.player.PlayerToggleFlightEvent; + +public class PassengerListener implements Listener { + private final PlayerManager playerManager; + + public PassengerListener(){ + this.playerManager = ServiceProvider.getSingleton(PlayerManager.class); + } + + @EventHandler + public void onPlayerFly(PlayerToggleFlightEvent e) { + org.bukkit.entity.Player bukkitPlayer = e.getPlayer(); + Player player = playerManager.getPlayer(bukkitPlayer); + if(!player.isSeated()) return; + + e.setCancelled(true); + bukkitPlayer.setFlying(true); + } + + @EventHandler + public void onQuit(PlayerQuitEvent e) { + org.bukkit.entity.Player bukkitPlayer = e.getPlayer(); + Player player = playerManager.getPlayer(bukkitPlayer); + if (!player.isSeated()) return; + + player.getSeatedOnContext().restore(player); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/identifier/RideIdentifier.java b/src/main/java/com/jverbruggen/jrides/models/identifier/RideIdentifier.java new file mode 100644 index 00000000..51379d0d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/identifier/RideIdentifier.java @@ -0,0 +1,5 @@ +package com.jverbruggen.jrides.models.identifier; + +public interface RideIdentifier { + String getIdentifierString(); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/identifier/SimpleRideIdentifier.java b/src/main/java/com/jverbruggen/jrides/models/identifier/SimpleRideIdentifier.java new file mode 100644 index 00000000..818dc386 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/identifier/SimpleRideIdentifier.java @@ -0,0 +1,14 @@ +package com.jverbruggen.jrides.models.identifier; + +public class SimpleRideIdentifier implements RideIdentifier { + private String name; + + public SimpleRideIdentifier(String name) { + this.name = name; + } + + @Override + public String getIdentifierString() { + return name; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/map/AbstractMap.java b/src/main/java/com/jverbruggen/jrides/models/map/AbstractMap.java new file mode 100644 index 00000000..b3f70aa7 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/map/AbstractMap.java @@ -0,0 +1,70 @@ +package com.jverbruggen.jrides.models.map; + +import java.util.Collection; + +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.MapMeta; +import org.bukkit.map.MapView; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.models.entity.Player; + +import dev.cerus.maps.api.ClientsideMap; +import dev.cerus.maps.api.graphics.ClientsideMapGraphics; +import dev.cerus.maps.version.VersionAdapterFactory; + +public abstract class AbstractMap implements VirtualMap { + private final MapView mapView; + private final ClientsideMapGraphics currentGraphics; + + public AbstractMap(MapView mapView){ + this.mapView = mapView; + this.currentGraphics = new ClientsideMapGraphics(); + } + + public void give(Player player){ + ItemStack itemStack = new ItemStack(Material.FILLED_MAP, 1); + MapMeta mapMeta = (MapMeta) itemStack.getItemMeta(); + assert mapMeta != null; + mapMeta.setMapView(mapView); + itemStack.setItemMeta(mapMeta); + + player.getBukkitPlayer().getInventory().addItem(itemStack); + + sendUpdate(player, true); + } + + public void sendUpdate(Collection players) { + if(players == null || players.isEmpty()) return; + + players.forEach(p -> sendUpdate(p, false)); + } + + protected ClientsideMapGraphics getGraphics(){ + return currentGraphics; + } + + private void sendUpdate(Player player, boolean delayed){ + int mapId = mapView.getId(); + + ClientsideMap clientsideMap = new ClientsideMap(mapId); + clientsideMap.draw(currentGraphics); + drawExtraGraphics(clientsideMap); + + if(delayed){ + Bukkit.getScheduler().runTaskLater(JRidesPlugin.getBukkitPlugin(), + () -> sendMap(clientsideMap, player), + 10L); + }else{ + sendMap(clientsideMap, player); + } + } + + private void sendMap(ClientsideMap map, Player player){ + map.sendTo(new VersionAdapterFactory().makeAdapter(), player.getBukkitPlayer()); + } + + protected abstract void drawExtraGraphics(ClientsideMap clientsideMap); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/map/AbstractMapFactory.java b/src/main/java/com/jverbruggen/jrides/models/map/AbstractMapFactory.java new file mode 100644 index 00000000..01bff202 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/map/AbstractMapFactory.java @@ -0,0 +1,88 @@ +package com.jverbruggen.jrides.models.map; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import javax.annotation.Nullable; + +import org.bukkit.Bukkit; +import org.bukkit.map.MapView; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.player.PlayerManager; + +public abstract class AbstractMapFactory { + private final PlayerManager playerManager; + private final int mapUpdateIntervalTicks; + private @Nullable Map maps; + + public AbstractMapFactory(int mapUpdateIntervalTicks){ + this.playerManager = ServiceProvider.getSingleton(PlayerManager.class); + this.mapUpdateIntervalTicks = mapUpdateIntervalTicks; + this.maps = null; + } + + public void initializeMaps(){ + this.maps = new HashMap<>(); + + loadMaps(); + + startUpdateCycle(); + } + + private void startUpdateCycle(){ + Bukkit.getScheduler().runTaskTimer(JRidesPlugin.getBukkitPlugin(), + () -> { + if(!hasMaps()) return; + Collection players = playerManager.getPlayers(); + + maps.values() + .forEach(m -> { + m.updateVisuals(); + m.sendUpdate(players); + }); + + }, this.mapUpdateIntervalTicks, this.mapUpdateIntervalTicks); + } + + public void addMap(String identifier, VirtualMap map){ + if(!hasMaps()) return; + maps.put(identifier, map); + } + + public VirtualMap getMap(String identifier){ + if(!hasMaps()) return null; + return maps.get(identifier); + } + + public Map getMaps() { + if(!hasMaps()) return null; + return maps; + } + + public abstract void loadMaps(); + + protected boolean hasMaps(){ + return this.maps != null; + } + + protected MapView createMapView(int mapId) throws MapCreationException { + if(mapId == -1){ + throw new MapCreationException("No ride overview map id configured"); + } + + @SuppressWarnings("deprecation") + MapView mapView = Bukkit.getMap(mapId); + if(mapView == null){ + throw new MapCreationException("Configured ride overview map id did not exist, first create the map and assign the ID to the coaster afterwards"); + } + + mapView.getRenderers().forEach(mapView::removeRenderer); + mapView.setLocked(true); + mapView.setTrackingPosition(false); + return mapView; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/map/MapCreationException.java b/src/main/java/com/jverbruggen/jrides/models/map/MapCreationException.java new file mode 100644 index 00000000..1c812385 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/map/MapCreationException.java @@ -0,0 +1,7 @@ +package com.jverbruggen.jrides.models.map; + +public class MapCreationException extends Exception{ + MapCreationException(String message){ + super(message); + } +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/models/map/VirtualMap.java b/src/main/java/com/jverbruggen/jrides/models/map/VirtualMap.java new file mode 100644 index 00000000..eaa3898b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/map/VirtualMap.java @@ -0,0 +1,11 @@ +package com.jverbruggen.jrides.models.map; + +import java.util.Collection; + +import com.jverbruggen.jrides.models.entity.Player; + +public interface VirtualMap { + void updateVisuals(); + void sendUpdate(Collection players); + void give(Player player); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/map/ridecounter/RideCounterMap.java b/src/main/java/com/jverbruggen/jrides/models/map/ridecounter/RideCounterMap.java new file mode 100644 index 00000000..68541948 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/map/ridecounter/RideCounterMap.java @@ -0,0 +1,87 @@ +package com.jverbruggen.jrides.models.map.ridecounter; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.models.map.AbstractMap; +import com.jverbruggen.jrides.models.ride.count.RideCounterRecord; +import com.jverbruggen.jrides.models.ride.count.RideCounterRecordRideCollection; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.RideCounterManager; +import dev.cerus.maps.api.ClientsideMap; +import dev.cerus.maps.api.Marker; +import dev.cerus.maps.api.graphics.ClientsideMapGraphics; +import org.bukkit.map.MapView; +import org.bukkit.map.MinecraftFont; + +import java.awt.image.BufferedImage; +import java.util.Map; + +public class RideCounterMap extends AbstractMap { + + private final RideHandle rideHandle; + private final Map lines; + private final String lineFormat; + private final BufferedImage backgroundImage; + private final Integer rideNameLine; + private final Integer typeLine; + private final String typeText; + private final byte primaryColor; + private final byte secondaryColor; + private final byte tertiaryColor; + private final RideCounterManager rideCounterManager; + + + public RideCounterMap(RideHandle rideHandle, MapView mapView, Map lines, String lineFormat, BufferedImage backgroundImage, + Integer rideNameLine, Integer typeLine, String typeText, byte primaryColor, byte secondaryColor, byte tertiaryColor) { + super(mapView); + this.rideHandle = rideHandle; + this.lines = lines; + this.lineFormat = lineFormat; + this.backgroundImage = backgroundImage; + this.rideNameLine = rideNameLine; + this.typeLine = typeLine; + this.typeText = typeText; + this.primaryColor = primaryColor; + this.secondaryColor = secondaryColor; + this.tertiaryColor = tertiaryColor; + this.rideCounterManager = ServiceProvider.getSingleton(RideCounterManager.class); + } + + public void updateVisuals() { + ClientsideMapGraphics currentGraphics = getGraphics(); + currentGraphics.drawImage(backgroundImage, 0, 0); + + // Draw the ride name if it is not null + if(rideNameLine != null) { + drawHorizontallyCenteredText(rideHandle.getRide().getDisplayName(), rideNameLine, primaryColor, currentGraphics); + } + + // Draw the type line if it is not null + if(typeLine != null) { + drawHorizontallyCenteredText(typeText, typeLine, secondaryColor, currentGraphics); + } + + // Get the ridebound record collection + RideCounterRecordRideCollection collection = rideCounterManager.getCollectionRideBound(rideHandle.getRide().getIdentifier()); + + // For each line, draw text on the map + lines.forEach((index, height) -> { + if(index >= collection.getRecords().size()) return; + RideCounterRecord record = collection.getRecords().get(index); + String line = lineFormat.replace("%RANK%", String.valueOf(index + 1)).replace("%COUNT%", String.valueOf(record.getRideCount())); + drawHorizontallyCenteredText(line, height, tertiaryColor, currentGraphics); + drawHorizontallyCenteredText(record.getPlayerName(), height + MinecraftFont.Font.getHeight() + 2, primaryColor, currentGraphics); + }); + } + + private void drawHorizontallyCenteredText(String text, int h, byte color, ClientsideMapGraphics graphics) { + MinecraftFont font = MinecraftFont.Font; + int x = (128 - font.getWidth(text)) / 2; + graphics.drawText(x, h, text, color, 1); + } + + @Override + protected void drawExtraGraphics(ClientsideMap clientsideMap){ + // Do nothing + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/models/map/ridecounter/RideCounterMapFactory.java b/src/main/java/com/jverbruggen/jrides/models/map/ridecounter/RideCounterMapFactory.java new file mode 100644 index 00000000..e1ab8b46 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/map/ridecounter/RideCounterMapFactory.java @@ -0,0 +1,190 @@ +package com.jverbruggen.jrides.models.map.ridecounter; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.AbstractRideHandle; +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.config.ride.RideCounterMapConfig; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.language.LanguageFileTag; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.map.AbstractMapFactory; +import com.jverbruggen.jrides.models.map.VirtualMap; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.RideManager; +import org.bukkit.Bukkit; +import org.bukkit.map.MapView; +import org.bukkit.map.MinecraftFont; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.File; +import java.util.*; + +public class RideCounterMapFactory extends AbstractMapFactory { + private static final int MAP_UPDATE_INTERVAL_TICKS = 20; + + private final RideManager rideManager; + private final LanguageFile languageFile; + private BufferedImage defaultBackgroundImage; + private final Map> linesPerType; + + public RideCounterMapFactory() { + super(MAP_UPDATE_INTERVAL_TICKS); + this.rideManager = ServiceProvider.getSingleton(RideManager.class); + this.languageFile = ServiceProvider.getSingleton(LanguageFile.class); + this.defaultBackgroundImage = null; + this.linesPerType = new HashMap<>(); + } + + public void loadMaps() { + defaultBackgroundImage = loadDefaultBackgroundImage(); + for(RideHandle rideHandle : rideManager.getRideHandles()) { + if(rideHandle instanceof AbstractRideHandle) { + loadRideCountMap((AbstractRideHandle) rideHandle); + } + } + } + + private BufferedImage loadDefaultBackgroundImage() { + File file = new File(JRidesPlugin.getBukkitPlugin().getDataFolder() + "/default_ridecountermap.png"); + if(!file.exists()) { + JRidesPlugin.getLogger().warning("Default ride counter map image not found! Using a blank background instead."); + }else { + try { + return ImageIO.read(file); + } catch (Exception e) { + JRidesPlugin.getLogger().warning("Failed to load default ride counter map image! Using a blank background instead."); + } + } + + BufferedImage image = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB); + for(int x = 0; x < 128; x++) { + for(int y = 0; y < 128; y++) { + image.setRGB(x, y, 0xFFFFFFFF); + } + } + return image; + } + + private void loadRideCountMap(AbstractRideHandle rideHandle) { + if(!hasMaps()) throw new RuntimeException("Ride counter maps was still null while loading ride counter map"); + + String rideIdentifier = rideHandle.getRide().getIdentifier(); + if(rideHandle.getRideCounterMapConfigs() == null || rideHandle.getRideCounterMapConfigs().getRideCounterMapConfigs() == null || rideHandle.getRideCounterMapConfigs().getRideCounterMapConfigs().isEmpty()) { + JRidesPlugin.getLogger().warning("No ride counter map configuration found for " + rideIdentifier + ", so skipping"); + return; + } + for(RideCounterMapConfig rideCounterMapConfig : rideHandle.getRideCounterMapConfigs().getRideCounterMapConfigs().values()) { + List mapIds = rideCounterMapConfig.getMapIds(); + List backgroundImages = rideCounterMapConfig.getBackgroundImages(); + int bufferPixels = 2 * MinecraftFont.Font.getHeight() + 2; + int mapIndex = 0; + int ridecountIndex = 0; + for(Integer mapId : mapIds) { + if(mapId == -1) { + JRidesPlugin.getLogger().warning("No ride counter map id configured for " + rideIdentifier + ", so skipping"); + continue; + } + + BufferedImage backgroundImage = null; + if(backgroundImages != null && backgroundImages.size() > mapIds.indexOf(mapId)) { + backgroundImage = backgroundImages.get(mapIds.indexOf(mapId)); + } + if(backgroundImage == null) backgroundImage = defaultBackgroundImage; + + // Check and set the line count for this map type + if(!linesPerType.containsKey(rideIdentifier)) { + linesPerType.put(rideIdentifier, new HashMap<>()); + } + Map typeMap = linesPerType.get(rideIdentifier); + if(typeMap.containsKey(rideCounterMapConfig.getRideCounterMapType())) { + Integer typeCount = typeMap.get(rideCounterMapConfig.getRideCounterMapType()); + if(rideCounterMapConfig.getLines().size() > typeCount) { + linesPerType.get(rideIdentifier).put(rideCounterMapConfig.getRideCounterMapType(), rideCounterMapConfig.getLines().size()); + } + }else { + linesPerType.get(rideIdentifier).put(rideCounterMapConfig.getRideCounterMapType(), rideCounterMapConfig.getLines().size()); + } + + Map mapLines = new HashMap<>(); + for(int i = 0; i < rideCounterMapConfig.getLines().size(); i++) { + int currentRangeMin = mapIndex * 128; + int currentRangeMax = currentRangeMin + 128; + int currentLine = rideCounterMapConfig.getLines().get(i); + + if(currentLine >= currentRangeMin - bufferPixels && currentLine < currentRangeMin) { + int difference = currentRangeMin - currentLine; + mapLines.put(ridecountIndex - 1, -difference); + continue; + } + + if(currentLine >= currentRangeMin && currentLine < currentRangeMax) { + mapLines.put(ridecountIndex++, currentLine - currentRangeMin); + } + } + + Integer rideNameLine = rideCounterMapConfig.getRideNameLine(); + Integer typeLine = rideCounterMapConfig.getTypeLine(); + String typeText = rideCounterMapConfig.getTypeText(); + byte primaryColor = rideCounterMapConfig.getPrimaryColor(); + byte secondaryColor = rideCounterMapConfig.getSecondaryColor(); + byte tertiaryColor = rideCounterMapConfig.getTertiaryColor(); + + // If this is the second map in a list, remove the ride name and type lines + if(mapIndex > 0) { + rideNameLine = null; + typeLine = null; + typeText = null; + } + + MapView mapView = Bukkit.getMap(mapId); + if(mapView == null) { + JRidesPlugin.getLogger().warning("No map found for id " + mapId + ". first create the map and assign the ID to the map configuration afterwards"); + continue; + } + + mapView.getRenderers().forEach(mapView::removeRenderer); + mapView.setLocked(true); + mapView.setTrackingPosition(false); + + RideCounterMap map = new RideCounterMap(rideHandle, mapView, mapLines, rideCounterMapConfig.getLineFormat(), backgroundImage, rideNameLine, typeLine, + typeText, primaryColor, secondaryColor, tertiaryColor); + addMap(String.format("%s %s_%s", rideIdentifier, rideCounterMapConfig.getRideCounterMapIdentifier(), mapIndex++), map); + } + } + } + + public List getBoardIdentifiersByRide(String rideIdentifier) { + Map maps = getMaps(); + if(maps == null) return new ArrayList<>(); + return maps.keySet().stream() + .filter(key -> key.startsWith(rideIdentifier)) + .map(key -> key.split(" ")[1]) + .toList(); + } + + public Integer getLineCount(String rideIdentifier, RideCounterMapType rideCounterMapType) { + if(!linesPerType.containsKey(rideIdentifier)) return 0; + if(!linesPerType.get(rideIdentifier).containsKey(rideCounterMapType)) return 0; + return linesPerType.get(rideIdentifier).get(rideCounterMapType); + } + + public void giveMap(Player player, RideHandle rideHandle, String rideCounterMapIdentifier) { + if(!hasMaps()) { + languageFile.sendMessage(player, LanguageFileField.NOTIFICATION_PLUGIN_STILL_LOADING); + return; + } + + String rideIdentifier = rideHandle.getRide().getIdentifier(); + VirtualMap map = getMap(String.format("%s %s", rideIdentifier, rideCounterMapIdentifier)); + if(map == null){ + languageFile.sendMessage(player, LanguageFileField.ERROR_RIDE_OVERVIEW_MAP_NOT_FOUND, + builder -> builder.add(LanguageFileTag.rideIdentifier, rideIdentifier)); + return; + } + + map.give(player); + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/models/map/ridecounter/RideCounterMapListener.java b/src/main/java/com/jverbruggen/jrides/models/map/ridecounter/RideCounterMapListener.java new file mode 100644 index 00000000..d218c91a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/map/ridecounter/RideCounterMapListener.java @@ -0,0 +1,87 @@ +package com.jverbruggen.jrides.models.map.ridecounter; + +import com.jverbruggen.jrides.event.ride.RideFinishedEvent; +import com.jverbruggen.jrides.event.ride.RideInitializedEvent; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.ride.count.RideCounterRecord; +import com.jverbruggen.jrides.models.ride.count.RideCounterRecordCollection; +import com.jverbruggen.jrides.models.ride.count.RideCounterRecordRideCollection; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.RideCounterManager; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class RideCounterMapListener implements Listener { + + private final RideCounterMapFactory rideCounterMapFactory; + private final RideCounterManager rideCounterManager; + + public RideCounterMapListener() { + this.rideCounterMapFactory = ServiceProvider.getSingleton(RideCounterMapFactory.class); + this.rideCounterManager = ServiceProvider.getSingleton(RideCounterManager.class); + } + + @EventHandler + public void onRidesInitialized(RideInitializedEvent e){ + rideCounterMapFactory.initializeMaps(); + } + + // TODO: Update this functionality to add support for all ride counter map types + @EventHandler + public void onRideFinished(RideFinishedEvent e) { + RideCounterRecordRideCollection rideBoundCollection = rideCounterManager.getCollectionRideBound(e.getRide().getIdentifier()); + int lineCount = rideCounterMapFactory.getLineCount(e.getRide().getIdentifier(), RideCounterMapType.TOP); + + // For each player in the event, check if they should be in the top map + for (Player player : e.getPlayers()) { + if(player == null || !player.getBukkitPlayer().isOnline()) continue; + + // If the player is already in the list, update the record + if (rideBoundCollection.existsOn(player)) { + rideBoundCollection.update(getPlayerRecord(player, e.getRide().getIdentifier())); + } else { + // If the list is not full, add the player + if (rideBoundCollection.getRecords().size() < lineCount) { + rideBoundCollection.add(getPlayerRecord(player, e.getRide().getIdentifier())); + }else { + // Loop through the records and find the lowest one + int lowest = 0; + for (int i = 0; i < rideBoundCollection.getRecords().size(); i++) { + if (rideBoundCollection.getRecords().get(i).getRideCount() < rideBoundCollection.getRecords().get(lowest).getRideCount()) { + lowest = i; + } + } + // If the player has more rides than the lowest, add them to the list + if(rideBoundCollection.getRecords().size() > lowest) { + if (getPlayerRecord(player, e.getRide().getIdentifier()).getRideCount() > rideBoundCollection.getRecords().get(lowest).getRideCount()) { + rideBoundCollection.add(player.getRideCounters().getRecords().get(e.getRide().getIdentifier())); + } + } + } + } + } + + // Sort the records by ride count + rideBoundCollection.getRecords().sort((o1, o2) -> o2.getRideCount() - o1.getRideCount()); + + // If the list is too long, remove the records with the lowest ride count to match the line count + while (rideBoundCollection.getRecords().size() > lineCount) { + int lowest = 0; + for (int i = 0; i < rideBoundCollection.getRecords().size(); i++) { + if (rideBoundCollection.getRecords().get(i).getRideCount() < rideBoundCollection.getRecords().get(lowest).getRideCount()) { + lowest = i; + } + } + rideBoundCollection.getRecords().remove(lowest); + } + + // Save the ride counter collection + rideCounterManager.saveToRideFile(e.getRide().getIdentifier(), rideBoundCollection); + } + + private RideCounterRecord getPlayerRecord(Player player, String rideIdentifier){ + RideCounterRecordCollection collection = rideCounterManager.getCollection(player.getIdentifier()); + return collection.findOrCreate(rideIdentifier, player); + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/models/map/ridecounter/RideCounterMapType.java b/src/main/java/com/jverbruggen/jrides/models/map/ridecounter/RideCounterMapType.java new file mode 100644 index 00000000..70730896 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/map/ridecounter/RideCounterMapType.java @@ -0,0 +1,7 @@ +package com.jverbruggen.jrides.models.map.ridecounter; + +public enum RideCounterMapType { + TOP, + DAILY, + WEEKLY +} diff --git a/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/MapScope.java b/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/MapScope.java new file mode 100644 index 00000000..8ca02fd9 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/MapScope.java @@ -0,0 +1,50 @@ +package com.jverbruggen.jrides.models.map.rideoverview; + +import com.jverbruggen.jrides.models.math.MathUtil; + +public class MapScope { + private static final int DRAW_SCREEN_SIZE = 128; + private static final int DRAW_MARKER_SIZE = 256; + + private int worldMinX; + private int worldMinZ; + private int worldMaxX; + private int worldMaxZ; + + public void setNew(int worldMinX, int worldMinZ, int worldMaxX, int worldMaxZ){ + // Preserving aspect ratio 1:1 + int dX = worldMaxX - worldMinX; + int dZ = worldMaxZ - worldMinZ; + if(dX > dZ){ + int delta = dX - dZ; + worldMinZ -= delta/2; + worldMaxZ += delta/2; + }else if(dZ > dX){ + int delta = dZ - dX; + worldMinX -= delta/2; + worldMaxX += delta/2; + } + + this.worldMinX = worldMinX; + this.worldMinZ = worldMinZ; + this.worldMaxX = worldMaxX; + this.worldMaxZ = worldMaxZ; + } + + public int toScreenX(int mapX){ + return (int)MathUtil.map(mapX, worldMinX, worldMaxX, 0, DRAW_SCREEN_SIZE-1); + } + + public int toScreenZ(int mapZ){ + return (int)MathUtil.map(mapZ, worldMinZ, worldMaxZ, 0, DRAW_SCREEN_SIZE-1); + } + + public int toScreenXMarker(int mapX){ + // TODO: Check out of bounds + return (int)MathUtil.map(mapX, worldMinX, worldMaxX, 0, DRAW_MARKER_SIZE-1); + } + + public int toScreenZMarker(int mapZ){ + return (int)MathUtil.map(mapZ, worldMinZ, worldMaxZ, 0, DRAW_MARKER_SIZE-1); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/RideOverviewMap.java b/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/RideOverviewMap.java new file mode 100644 index 00000000..ab6ecd7d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/RideOverviewMap.java @@ -0,0 +1,85 @@ +package com.jverbruggen.jrides.models.map.rideoverview; + +import com.jverbruggen.jrides.models.map.AbstractMap; +import com.jverbruggen.jrides.models.math.Vector2; +import com.jverbruggen.jrides.models.ride.section.Section; +import dev.cerus.maps.api.ClientsideMap; +import dev.cerus.maps.api.graphics.ClientsideMapGraphics; +import dev.cerus.maps.api.graphics.ColorCache; +import org.bukkit.map.MapView; + +import java.util.List; + +public class RideOverviewMap extends AbstractMap { + private static final byte COLOR_BORDER_DARK = ColorCache.rgbToMap(55,55,55); + private static final byte COLOR_BORDER_DARK_LIGHTER = ColorCache.rgbToMap(110,110,110); + + private static final byte COLOR_BACKGROUND = ColorCache.rgbToMap(190,190,190); + private static final byte COLOR_DEFAULT = ColorCache.rgbToMap(50,50,50); + private static final byte COLOR_OCCUPIED = ColorCache.rgbToMap(27, 181, 0); + private static final byte COLOR_RESERVED = ColorCache.rgbToMap(214, 143, 0); + + private final List sectionVisuals; + private List trainVisuals; + + public RideOverviewMap(MapView mapView, List sectionVisuals, List trainVisuals) { + super(mapView); + this.sectionVisuals = sectionVisuals; + this.trainVisuals = trainVisuals; + } + + public void updateVisuals(){ + ClientsideMapGraphics currentGraphics = getGraphics(); + currentGraphics.fillComplete(COLOR_BACKGROUND); + addBorder(currentGraphics); + + for(SectionVisual sectionVisual : sectionVisuals){ + List drawPoints = sectionVisual.getDrawPoints(); + + Section section = sectionVisual.getSection(); + byte color = getSectionColor(section); + + if(drawPoints.size() <= 1) continue; + Vector2 prev = drawPoints.get(0); + for(int i = 1; i < drawPoints.size(); i++){ + Vector2 cur = drawPoints.get(i); + + currentGraphics.drawLine((int)prev.x, (int)prev.y, (int)cur.x, (int)cur.y, color, 1f); + + prev = cur; + } + } + + for(TrainVisual visual : trainVisuals){ + visual.update(); + } + } + + private byte getSectionColor(Section section){ + if(section.isOccupied()) return COLOR_OCCUPIED; + else if(section.getReservedBy() != null) return COLOR_RESERVED; + else return COLOR_DEFAULT; + } + + @Override + protected void drawExtraGraphics(ClientsideMap clientsideMap){ + trainVisuals.forEach(v -> clientsideMap.addMarker(v.getMarker())); + } + + + private void addBorder(ClientsideMapGraphics graphics){ + int borderWidth = 6; + int shadeWidth = 3; + int size = 128; + + graphics.fillRect(0, 0, size, shadeWidth, COLOR_BORDER_DARK, 1f); + graphics.fillRect(0, 0, shadeWidth, size, COLOR_BORDER_DARK, 1f); + graphics.fillRect(size-shadeWidth, 0, shadeWidth, size, COLOR_BORDER_DARK, 1f); + graphics.fillRect(0, size-shadeWidth, size, shadeWidth, COLOR_BORDER_DARK, 1f); + + graphics.fillRect(shadeWidth, shadeWidth, size-borderWidth, shadeWidth, COLOR_BORDER_DARK_LIGHTER, 1f); + graphics.fillRect(shadeWidth, shadeWidth, shadeWidth, size-borderWidth, COLOR_BORDER_DARK_LIGHTER, 1f); + graphics.fillRect(size-borderWidth, shadeWidth, shadeWidth, size-borderWidth, COLOR_BORDER_DARK_LIGHTER, 1f); + graphics.fillRect(shadeWidth, size-borderWidth, size-borderWidth, shadeWidth, COLOR_BORDER_DARK_LIGHTER, 1f); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/RideOverviewMapFactory.java b/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/RideOverviewMapFactory.java new file mode 100644 index 00000000..0430960b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/RideOverviewMapFactory.java @@ -0,0 +1,81 @@ +package com.jverbruggen.jrides.models.map.rideoverview; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.language.LanguageFileTag; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.map.AbstractMapFactory; +import com.jverbruggen.jrides.models.map.MapCreationException; +import com.jverbruggen.jrides.models.map.VirtualMap; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.RideManager; +import org.bukkit.map.MapView; + +import java.util.List; + +public class RideOverviewMapFactory extends AbstractMapFactory { + private static final int MAP_UPDATE_INTERVAL_TICKS = 1; + + private final SectionVisualFactory sectionVisualFactory; + private final TrainVisualFactory trainVisualFactory; + private final RideManager rideManager; + private final LanguageFile languageFile; + + public RideOverviewMapFactory(){ + super(MAP_UPDATE_INTERVAL_TICKS); + sectionVisualFactory = ServiceProvider.getSingleton(SectionVisualFactory.class); + trainVisualFactory = ServiceProvider.getSingleton(TrainVisualFactory.class); + rideManager = ServiceProvider.getSingleton(RideManager.class); + languageFile = ServiceProvider.getSingleton(LanguageFile.class); + } + + public void loadMaps(){ + for(RideHandle rideHandle : rideManager.getRideHandles()){ + if(rideHandle instanceof CoasterHandle) + loadRideOverviewMap((CoasterHandle) rideHandle); + } + } + + public void giveMap(Player player, CoasterHandle coasterHandle){ + if(!hasMaps()){ + languageFile.sendMessage(player, LanguageFileField.NOTIFICATION_PLUGIN_STILL_LOADING); + return; + } + + String rideIdentifier = coasterHandle.getRide().getIdentifier(); + VirtualMap map = getMap(rideIdentifier); + if(map == null){ + languageFile.sendMessage(player, LanguageFileField.ERROR_RIDE_OVERVIEW_MAP_NOT_FOUND, + builder -> builder.add(LanguageFileTag.rideIdentifier, rideIdentifier)); + return; + } + + map.give(player); + } + + private void loadRideOverviewMap(CoasterHandle coasterHandle){ + if(!hasMaps()) throw new RuntimeException("Ride overview maps was still null while loading overview map"); + + String rideIdentifier = coasterHandle.getRide().getIdentifier(); + int mapId = coasterHandle.getRideOverviewMapId(); + + MapView mapView; + try { + mapView = createMapView(mapId); + } catch (MapCreationException e) { + JRidesPlugin.getLogger().warning("An error occured while loading ride overview map for " + rideIdentifier + ": " + e.getMessage()); + return; + } + + MapScope mapScope = new MapScope(); + + List sectionVisuals = sectionVisualFactory.createVisuals(coasterHandle, mapScope); + List trainVisuals = trainVisualFactory.createVisuals(coasterHandle, mapScope); + + VirtualMap map = new RideOverviewMap(mapView, sectionVisuals, trainVisuals); + addMap(rideIdentifier, map); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/RideOverviewMapListener.java b/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/RideOverviewMapListener.java new file mode 100644 index 00000000..ffa43554 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/RideOverviewMapListener.java @@ -0,0 +1,19 @@ +package com.jverbruggen.jrides.models.map.rideoverview; + +import com.jverbruggen.jrides.event.ride.RideInitializedEvent; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class RideOverviewMapListener implements Listener { + private final RideOverviewMapFactory rideOverviewMapFactory; + + public RideOverviewMapListener() { + this.rideOverviewMapFactory = ServiceProvider.getSingleton(RideOverviewMapFactory.class); + } + + @EventHandler + public void onRidesInitialized(RideInitializedEvent e){ + rideOverviewMapFactory.initializeMaps(); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/SectionVisual.java b/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/SectionVisual.java new file mode 100644 index 00000000..0d3baad9 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/SectionVisual.java @@ -0,0 +1,29 @@ +package com.jverbruggen.jrides.models.map.rideoverview; + +import com.jverbruggen.jrides.models.math.Vector2; +import com.jverbruggen.jrides.models.ride.section.Section; + +import java.util.ArrayList; +import java.util.List; + +public class SectionVisual { + private Section section; + private List drawPoints; + + public SectionVisual(Section section) { + this.section = section; + this.drawPoints = new ArrayList<>(); + } + + public Section getSection() { + return section; + } + + public List getDrawPoints() { + return drawPoints; + } + + public void addDrawPoint(Vector2 point){ + drawPoints.add(point); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/SectionVisualFactory.java b/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/SectionVisualFactory.java new file mode 100644 index 00000000..2808379e --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/SectionVisualFactory.java @@ -0,0 +1,113 @@ +package com.jverbruggen.jrides.models.map.rideoverview; + +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.models.math.Vector2; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.frame.AutoTrackUpdateFrame; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.section.Section; + +import java.util.*; + +class SectionVectorCombi{ + private final Section section; + private final Vector3 vector3; + + public SectionVectorCombi(Section section, Vector3 vector3) { + this.section = section; + this.vector3 = vector3; + } + + public Section getSection() { + return section; + } + + public Vector3 getVector3() { + return vector3; + } +} + +public class SectionVisualFactory { + public List createVisuals(CoasterHandle handle, MapScope mapScope){ + List
sections = handle.getTrack().getSections(); + + // For normalization + int minX = Integer.MAX_VALUE; + int minZ = Integer.MAX_VALUE; + int maxX = Integer.MIN_VALUE; + int maxZ = Integer.MIN_VALUE; + int borderPadding = 14; + + List locations3D = new ArrayList<>(); + for(Section section : sections){ + Frame startFrame = section.getStartFrame().clone(); + Frame endFrame = section.getEndFrame().clone(); + + int distance = getForwardDistance(startFrame.getTrack(), startFrame, endFrame); + int interval = 100; + int amount = Math.floorDiv(distance, interval); + + locations3D.add(new SectionVectorCombi(section, section.getLocationFor(startFrame))); + + AutoTrackUpdateFrame walkingFrame = AutoTrackUpdateFrame.of(startFrame); + for(int i = 0; i < amount; i++){ + walkingFrame.add(interval); + + Vector3 location = section.getLocationFor(walkingFrame); + + locations3D.add(new SectionVectorCombi(section, location)); + + // Normalization preparations, getting outer bounds + int x = location.getBlockX(); + int z = location.getBlockZ(); + + if(x < minX) minX = x; + else if(x > maxX) maxX = x; + + if(z < minZ) minZ = z; + else if(z > maxZ) maxZ = z; + } + + locations3D.add(new SectionVectorCombi(section, section.getLocationFor(endFrame))); + } + + minX -= borderPadding; + minZ -= borderPadding; + maxX += borderPadding; + maxZ += borderPadding; + + mapScope.setNew(minX, minZ, maxX, maxZ); + + // Normalize to 2d + Map sectionVisuals = new HashMap<>(); + for(SectionVectorCombi pack : locations3D){ + Vector3 location3D = pack.getVector3(); + Section section = pack.getSection(); + + int x = mapScope.toScreenX((int)location3D.getX()); + int z = mapScope.toScreenZ((int)location3D.getZ()); + + SectionVisual visual = sectionVisuals.get(section); + if(visual == null){ + visual = new SectionVisual(section); + sectionVisuals.put(section, visual); + } + + visual.addDrawPoint(new Vector2(x, z)); + } + + return new ArrayList<>(sectionVisuals.values()); + } + + private int getForwardDistance(Track track, Frame from, Frame toForwards){ + int fromValue = from.getValue(); + int toValue = toForwards.getValue(); + + if(toValue >= fromValue) return toValue - fromValue; + + int beforeCycleDistance = track.getUpperFrame() - fromValue; + int afterCycleDistance = toValue - track.getLowerFrame(); + return beforeCycleDistance + afterCycleDistance; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/TrainVisual.java b/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/TrainVisual.java new file mode 100644 index 00000000..c1a47a94 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/TrainVisual.java @@ -0,0 +1,39 @@ +package com.jverbruggen.jrides.models.map.rideoverview; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import dev.cerus.maps.api.Marker; + +public class TrainVisual { + private final TrainHandle trainHandle; + private final MapScope mapScope; + private Marker marker; + + public TrainVisual(TrainHandle trainHandle, MapScope mapScope) { + this.trainHandle = trainHandle; + this.mapScope = mapScope; + this.marker = new Marker(0,0, + (byte)0, // Marker direction + (byte)4, // Marker type + true); + } + + public int getX(){ + return (int) trainHandle.getTrain().getCurrentLocation().getX(); + } + + public int getZ(){ + return (int) trainHandle.getTrain().getCurrentLocation().getZ(); + } + + public void update(){ + int markerX = mapScope.toScreenXMarker(getX()); + int markerZ = mapScope.toScreenZMarker(getZ()); + + marker.setX(markerX); + marker.setY(markerZ); + } + + public Marker getMarker(){ + return marker; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/TrainVisualFactory.java b/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/TrainVisualFactory.java new file mode 100644 index 00000000..f64e0ba4 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/map/rideoverview/TrainVisualFactory.java @@ -0,0 +1,17 @@ +package com.jverbruggen.jrides.models.map.rideoverview; + +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.animator.coaster.TrainHandle; + +import java.util.List; +import java.util.stream.Collectors; + +public class TrainVisualFactory { + public List createVisuals(CoasterHandle handle, MapScope mapScope){ + List trains = handle.getTrains(); + + return trains.stream() + .map(t -> new TrainVisual(t, mapScope)) + .collect(Collectors.toList()); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/math/ArmorStandPose.java b/src/main/java/com/jverbruggen/jrides/models/math/ArmorStandPose.java new file mode 100644 index 00000000..cc95d18e --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/math/ArmorStandPose.java @@ -0,0 +1,53 @@ +/** + * This code has been kindly borrowed from bergerkiller's BKCommonLib + * + * MIT License + * + * Copyright (C) 2013-2015 bergerkiller Copyright (C) 2016-2020 Berger Healer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, and/or sublicense the Software, + * and to permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.jverbruggen.jrides.models.math; + +public class ArmorStandPose { + public static Vector3 getArmorStandPose(Quaternion rotation) { + double qx = rotation.getX(); + double qy = rotation.getY(); + double qz = rotation.getZ(); + double qw = rotation.getW(); + + double rx = 1.0 + 2.0 * (-qy * qy - qz * qz); + double ry = 2.0 * (qx * qy + qz * qw); + double rz = 2.0 * (qx * qz - qy * qw); + double uz = 2.0 * (qy * qz + qx * qw); + double fz = 1.0 + 2.0 * (-qx * qx - qy * qy); + + if(Math.abs(rz) < (1.0 - 1E-15)) { + return new Vector3(MathUtil.atan2(uz, fz), fastAsin(rz), MathUtil.atan2(-ry, rx)); + }else { + final double sign = (rz < 0) ? -1.0 : 1.0; + return new Vector3(0.0, sign * 90.0, -sign * 2.0 * MathUtil.atan2(qx, qw)); + } + } + + private static float fastAsin(double x) { + return MathUtil.atan(x / Math.sqrt(1.0 - x * x)); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/math/CommonTrigMath.java b/src/main/java/com/jverbruggen/jrides/models/math/CommonTrigMath.java new file mode 100644 index 00000000..1b8fd68a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/math/CommonTrigMath.java @@ -0,0 +1,68 @@ +/** + * This code has been kindly borrowed from bergerkiller's BKCommonLib + * + * MIT License + * + * Copyright (C) 2013-2015 bergerkiller Copyright (C) 2016-2020 Berger Healer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, and/or sublicense the Software, + * and to permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.jverbruggen.jrides.models.math; + +public class CommonTrigMath { + static final double sq2p1 = 2.414213562373095048802e0; + static final double sq2m1 = .414213562373095048802e0; + static final double p4 = .161536412982230228262e2; + static final double p3 = .26842548195503973794141e3; + static final double p2 = .11530293515404850115428136e4; + static final double p1 = .178040631643319697105464587e4; + static final double p0 = .89678597403663861959987488e3; + static final double q4 = .5895697050844462222791e2; + static final double q3 = .536265374031215315104235e3; + static final double q2 = .16667838148816337184521798e4; + static final double q1 = .207933497444540981287275926e4; + static final double q0 = .89678597403663861962481162e3; + static final double PIO2 = 1.5707963267948966135E0; + + private static double mxatan(double arg) { + double argsq = arg * arg, value; + + value = ((((p4 * argsq + p3) * argsq + p2) * argsq + p1) * argsq + p0); + value = value / (((((argsq + q4) * argsq + q3) * argsq + q2) * argsq + q1) * argsq + q0); + return value * arg; + } + + private static double msatan(double arg) { + return arg < sq2m1 ? mxatan(arg) + : arg > sq2p1 ? PIO2 - mxatan(1 / arg) + : PIO2 / 2 + mxatan((arg - 1) / (arg + 1)); + } + + public static double atan(double arg) { + return arg > 0 ? msatan(arg) : -msatan(-arg); + } + + public static double atan2(double arg1, double arg2) { + if (arg1 + arg2 == arg1) + return arg1 >= 0 ? PIO2 : -PIO2; + arg1 = atan(arg1 / arg2); + return arg2 < 0 ? arg1 <= 0 ? arg1 + Math.PI : arg1 - Math.PI : arg1; + } +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/models/math/FaceUtil.java b/src/main/java/com/jverbruggen/jrides/models/math/FaceUtil.java new file mode 100644 index 00000000..4a79b044 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/math/FaceUtil.java @@ -0,0 +1,508 @@ +/** + * This code has been kindly borrowed from bergerkiller's BKCommonLib + * + * MIT License + * + * Copyright (C) 2013-2015 bergerkiller Copyright (C) 2016-2020 Berger Healer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, and/or sublicense the Software, + * and to permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.jverbruggen.jrides.models.math; + +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.util.Vector; + +import java.util.EnumMap; + +public class FaceUtil { + + public static final BlockFace[] AXIS = new BlockFace[4]; + public static final BlockFace[] RADIAL = {BlockFace.WEST, BlockFace.NORTH_WEST, BlockFace.NORTH, BlockFace.NORTH_EAST, BlockFace.EAST, BlockFace.SOUTH_EAST, BlockFace.SOUTH, BlockFace.SOUTH_WEST}; + public static final BlockFace[] BLOCK_SIDES = {BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST, BlockFace.UP, BlockFace.DOWN}; + public static final BlockFace[] ATTACHEDFACES = {BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST, BlockFace.UP}; + public static final BlockFace[] ATTACHEDFACESDOWN = BLOCK_SIDES; + private static final EnumMap notches = new EnumMap<>(BlockFace.class); + + static { + for (int i = 0; i < RADIAL.length; i++) { + notches.put(RADIAL[i], i); + } + for (int i = 0; i < AXIS.length; i++) { + AXIS[i] = RADIAL[i << 1]; + } + } + + /** + * Gets the Notch integer representation of a BlockFace
+ * These are the horizontal faces, which exclude up and down, and sub-faces + *

+ * The following mapping is maintained: + *
    + *
  • BlockFace.WEST = 0 + *
  • BlockFace.NORTH_WEST = 1 + *
  • BlockFace.NORTH = 2 + *
  • BlockFace.NORTH_EAST = 3 + *
  • BlockFace.EAST = 4 + *
  • BlockFace.SOUTH_EAST = 5 + *
  • BlockFace.SOUTH = 6 + *
  • BlockFace.SOUTH_WEST = 7 + *
  • Invalid = 0 + *
+ * + * @param face to get + * @return Notch of the face + */ + public static int faceToNotch(BlockFace face) { + Integer notch = notches.get(face); + return notch == null ? 0 : notch; + } + + /** + * Checks whether a given face is an offset along the X-axis. This is true for: + *
    + *
  • BlockFace.EAST + *
  • BlockFace.WEST + *
+ * + * @param face to check + * @return True if it is along the X-axis, False if not + */ + public static boolean isAlongX(BlockFace face) { + return face.getModX() != 0 && face.getModZ() == 0; + } + + /** + * Checks whether a given face is an offset along the Y-axis. This is true for: + *
    + *
  • BlockFace.UP + *
  • BlockFace.DOWN + *
+ * + * @param face to check + * @return True if it is along the Y-axis, False if not + */ + public static boolean isAlongY(BlockFace face) { + return isVertical(face); + } + + /** + * Checks whether a given face is an offset along the Z-axis. This is true for: + *
    + *
  • BlockFace.SOUTH + *
  • BlockFace.NORTH + *
+ * + * @param face to check + * @return True if it is along the Z-axis, False if not + */ + public static boolean isAlongZ(BlockFace face) { + return face.getModZ() != 0 && face.getModX() == 0; + } + + /** + * Gets the Block Face at the notch index modulus 8 specified
+ * These are the horizontal faces, which exclude up and down, and sub-faces + *

+ * The following mapping is maintained: + *
    + *
  • 0 = BlockFace.WEST + *
  • 1 = BlockFace.NORTH_WEST + *
  • 2 = BlockFace.NORTH + *
  • 3 = BlockFace.NORTH_EAST + *
  • 4 = BlockFace.EAST + *
  • 5 = BlockFace.SOUTH_EAST + *
  • 6 = BlockFace.SOUTH + *
  • 7 = BlockFace.SOUTH_WEST + *
  • 8 = BlockFace.WEST + *
  • 9 = BlockFace.NORTH_WEST + *
  • etc. + *
+ * + * @param notch to get + * @return BlockFace of the notch + */ + public static BlockFace notchToFace(int notch) { + return RADIAL[notch & 0x7]; + } + + /** + * Adds a certain amount of notches (n of 45-degree angles) to a BlockFace + * + * @param face input + * @param notchOffset to offset the input by + * @return face input offset by notchOffset notches + */ + public static BlockFace notchFaceOffset(BlockFace face, int notchOffset) { + return notchToFace(faceToNotch(face) + notchOffset); + } + + /** + * Rotates a given Block Face horizontally + * + * @param from face + * @param notchCount to rotate at + * @return rotated face + */ + public static BlockFace rotate(BlockFace from, int notchCount) { + return notchToFace(faceToNotch(from) + notchCount); + } + + /** + * Combines two non-subcardinal faces into one face
+ * - NORTH and WEST returns NORTH_WEST
+ * - NORTH and SOUTH returns NORTH (not possible to combine) + * + * @param from face to combined + * @param to face to combined + * @return the combined face + */ + public static BlockFace combine(BlockFace from, BlockFace to) { + if (from == BlockFace.NORTH) { + if (to == BlockFace.WEST) { + return BlockFace.NORTH_WEST; + } else if (to == BlockFace.EAST) { + return BlockFace.NORTH_EAST; + } + } else if (from == BlockFace.EAST) { + if (to == BlockFace.NORTH) { + return BlockFace.NORTH_EAST; + } else if (to == BlockFace.SOUTH) { + return BlockFace.SOUTH_EAST; + } + } else if (from == BlockFace.SOUTH) { + if (to == BlockFace.WEST) { + return BlockFace.SOUTH_WEST; + } else if (to == BlockFace.EAST) { + return BlockFace.SOUTH_EAST; + } + } else if (from == BlockFace.WEST) { + if (to == BlockFace.NORTH) { + return BlockFace.NORTH_WEST; + } else if (to == BlockFace.SOUTH) { + return BlockFace.SOUTH_WEST; + } + } + return from; + } + + /** + * Gets all the individual faces represented by a Block Face
+ * - NORTH_WEST returns NORTH and WEST
+ * - NORTH returns NORTH and SOUTH
+ * + * @param main face to get the faces for + * @return an array of length 2 containing all the faces + */ + public static BlockFace[] getFaces(BlockFace main) { + switch (main) { + case SOUTH_EAST: + return new BlockFace[]{BlockFace.SOUTH, BlockFace.EAST}; + case SOUTH_WEST: + return new BlockFace[]{BlockFace.SOUTH, BlockFace.WEST}; + case NORTH_EAST: + return new BlockFace[]{BlockFace.NORTH, BlockFace.EAST}; + case NORTH_WEST: + return new BlockFace[]{BlockFace.NORTH, BlockFace.WEST}; + default: + return new BlockFace[]{main, main.getOppositeFace()}; + } + } + + /** + * Gets the direction a minecart faces when on a given track + * + * @param raildirection of the rails + * @return minecart direction + */ + public static BlockFace getRailsCartDirection(final BlockFace raildirection) { + switch (raildirection) { + case NORTH_EAST: + case SOUTH_WEST: + return BlockFace.NORTH_WEST; + case NORTH_WEST: + case SOUTH_EAST: + return BlockFace.SOUTH_WEST; + default: + return raildirection; + } + } + + /** + * Gets the rail direction from a Direction
+ * NORTH becomes SOUTH and WEST becomes EAST + * + * @param direction to convert + * @return rail direction + */ + public static BlockFace toRailsDirection(BlockFace direction) { + switch (direction) { + case NORTH: + return BlockFace.SOUTH; + case WEST: + return BlockFace.EAST; + default: + return direction; + } + } + + /** + * Gets whether a given Block Face is sub-cardinal (such as NORTH_WEST) + * + * @param face to check + * @return True if sub-cardinal, False if not + */ + public static boolean isSubCardinal(final BlockFace face) { + switch (face) { + case NORTH_EAST: + case SOUTH_EAST: + case SOUTH_WEST: + case NORTH_WEST: + return true; + default: + return false; + } + } + + /** + * Checks whether a face is up or down + * + * @param face to check + * @return True if it is UP or DOWN + */ + public static boolean isVertical(BlockFace face) { + return face == BlockFace.UP || face == BlockFace.DOWN; + } + + /** + * Gets the BlockFace.UP or BlockFace.DOWN constant based on the up + * parameter + * + * @param up parameter + * @return UP if up is true, DOWN if up is false + */ + public static BlockFace getVertical(boolean up) { + return up ? BlockFace.UP : BlockFace.DOWN; + } + + /** + * Gets the BlockFace.UP or BlockFace.DOWN based on the delta-y parameter + * + * @param dy parameter + * @return UP if dy >= 0, DOWN if dy < 0 + */ + public static BlockFace getVertical(double dy) { + return getVertical(dy >= 0.0); + } + + /** + * Gets whether two faces have a sub-cardinal difference or less + * + * @param face1 to check + * @param face2 to check + * @return True if the difference <= 45 degrees + */ + public static boolean hasSubDifference(final BlockFace face1, final BlockFace face2) { + return getFaceYawDifference(face1, face2) <= 45; + } + + /** + * Gets the Vector direction from a Block Face + * + * @param face to use + * @param length of the vector + * @return Vector of the direction and length + */ + public static Vector faceToVector(BlockFace face, double length) { + return faceToVector(face).multiply(length); + } + + /** + * Gets the Vector direction from a Block Face + * + * @param face to use + * @return Vector of the direction and length 1 + */ + public static Vector faceToVector(BlockFace face) { + return new Vector(face.getModX(), face.getModY(), face.getModZ()); + } + + /** + * Gets the Block Face direction to go from one point to another + * + * @param from point + * @param to point + * @param useSubCardinalDirections setting + * @return the Block Face of the direction + */ + public static BlockFace getDirection(Location from, Location to, boolean useSubCardinalDirections) { + return getDirection(to.getX() - from.getX(), to.getZ() - from.getZ(), useSubCardinalDirections); + } + + /** + * Gets the Block Face direction to go from one block to another + * + * @param from block + * @param to block + * @param useSubCardinalDirections setting + * @return the Block Face of the direction + */ + public static BlockFace getDirection(Block from, Block to, boolean useSubCardinalDirections) { + return getDirection(to.getX() - from.getX(), to.getZ() - from.getZ(), useSubCardinalDirections); + } + + /** + * Gets the Block Face direction to go into the movement vector direction + * + * @param movement vector + * @return the Block Face of the direction + */ + public static BlockFace getDirection(Vector movement) { + return getDirection(movement, true); + } + + /** + * Gets the Block Face direction to go into the movement vector direction + * + * @param movement vector + * @param useSubCardinalDirections setting + * @return the Block Face of the direction + */ + public static BlockFace getDirection(Vector movement, boolean useSubCardinalDirections) { + return getDirection(movement.getX(), movement.getZ(), useSubCardinalDirections); + } + + /** + * Gets the Block Face direction to go into the movement vector direction + * + * @param dx vector axis + * @param dz vector axis + * @param useSubCardinalDirections setting + * @return the Block Face of the direction + */ + public static BlockFace getDirection(final double dx, final double dz, boolean useSubCardinalDirections) { + return yawToFace(MathUtil.getLookAtYaw(dx, dz), useSubCardinalDirections); + } + + /** + * Gets the yaw angle in degrees difference between two Block Faces + * + * @param face1 + * @param face2 + * @return angle in degrees + */ + public static int getFaceYawDifference(BlockFace face1, BlockFace face2) { + return MathUtil.getAngleDifference(faceToYaw(face1), faceToYaw(face2)); + } + + /** + * Gets the co-sinus value from a Block Face treated as an Angle + * + * @param face to get the co-sinus value from + * @return co-sinus value + */ + public static double cos(final BlockFace face) { + switch (face) { + case SOUTH_WEST: + case NORTH_WEST: + return -MathUtil.HALFROOTOFTWO; + case SOUTH_EAST: + case NORTH_EAST: + return MathUtil.HALFROOTOFTWO; + case EAST: + return 1; + case WEST: + return -1; + default: + return 0; + } + } + + /** + * Gets the sinus value from a Block Face treated as an Angle + * + * @param face to get the sinus value from + * @return sinus value + */ + public static double sin(final BlockFace face) { + switch (face) { + case NORTH_EAST: + case NORTH_WEST: + return -MathUtil.HALFROOTOFTWO; + case SOUTH_WEST: + case SOUTH_EAST: + return MathUtil.HALFROOTOFTWO; + case NORTH: + return -1; + case SOUTH: + return 1; + default: + return 0; + } + } + + /** + * Gets the angle from a horizontal Block Face. The following mapping is used:
+ *
  • BlockFace.WEST = 0 + *
  • BlockFace.NORTH_WEST = 45 + *
  • BlockFace.NORTH = 90 + *
  • BlockFace.NORTH_EAST = 135 + *
  • BlockFace.EAST = 180 + *
  • BlockFace.SOUTH_EAST = -135 + *
  • BlockFace.SOUTH = -90 + *
  • BlockFace.SOUTH_WEST = -45 + *
  • Invalid = 0 + * + * @param face to get the angle for + * @return face angle + */ + public static int faceToYaw(final BlockFace face) { + return MathUtil.wrapAngle(45 * faceToNotch(face)); + } + + /** + * Gets the horizontal Block Face from a given yaw angle
    + * This includes the NORTH_WEST faces + * + * @param yaw angle + * @return The Block Face of the angle + */ + public static BlockFace yawToFace(float yaw) { + return yawToFace(yaw, true); + } + + /** + * Gets the horizontal Block Face from a given yaw angle + * + * @param yaw angle + * @param useSubCardinalDirections setting, True to allow NORTH_WEST to be + * returned + * @return The Block Face of the angle + */ + public static BlockFace yawToFace(float yaw, boolean useSubCardinalDirections) { + if (useSubCardinalDirections) { + return RADIAL[Math.round(yaw / 45f) & 0x7]; + } else { + return AXIS[Math.round(yaw / 90f) & 0x3]; + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/models/math/MathUtil.java b/src/main/java/com/jverbruggen/jrides/models/math/MathUtil.java new file mode 100644 index 00000000..3a9dd001 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/math/MathUtil.java @@ -0,0 +1,963 @@ +/** + * This code has been kindly borrowed from bergerkiller's BKCommonLib + * + * MIT License + * + * Copyright (C) 2013-2015 bergerkiller Copyright (C) 2016-2020 Berger Healer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, and/or sublicense the Software, + * and to permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.jverbruggen.jrides.models.math; + +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.entity.Entity; +import org.bukkit.util.Vector; + +public class MathUtil { + + private static final int CHUNK_BITS = 4; + private static final int CHUNK_VALUES = 16; + public static final float DEGTORAD = 0.017453293F; + public static final float RADTODEG = 57.29577951F; + public static final double HALFROOTOFTWO = 0.707106781; + + public static double lengthSquared(double... values) { + double rval = 0; + for (double value : values) { + rval += value * value; + } + return rval; + } + + public static double length(double... values) { + return Math.sqrt(lengthSquared(values)); + } + + public static double distance(double x1, double y1, double x2, double y2) { + return length(x1 - x2, y1 - y2); + } + + public static double distanceSquared(double x1, double y1, double x2, double y2) { + return lengthSquared(x1 - x2, y1 - y2); + } + + public static double distance(double x1, double y1, double z1, double x2, double y2, double z2) { + return length(x1 - x2, y1 - y2, z1 - z2); + } + + public static double distanceSquared(double x1, double y1, double z1, double x2, double y2, double z2) { + return lengthSquared(x1 - x2, y1 - y2, z1 - z2); + } + + /** + * Gets a percentage and round it with a cusotm amound of decimals + * + * @param subtotal to get percentags for + * @param total to use as 100% value + * @param decimals to round with + * @return Percentage for subtotal with custom decimals + */ + public static double getPercentage(int subtotal, int total, int decimals) { + return round(getPercentage(subtotal, total), decimals); + } + + /** + * Gets a percentags of 2 values + * + * @param subtotal to get percentage for + * @param total to sue as 100% value + * @return percentage + */ + public static double getPercentage(int subtotal, int total) { + return ((float) subtotal / (float) total) * 100; + } + + /** + * Gets the angle difference between two angles + * + * @param angle1 + * @param angle2 + * @return angle difference + */ + public static int getAngleDifference(int angle1, int angle2) { + return Math.abs(wrapAngle(angle1 - angle2)); + } + + /** + * Gets the angle difference between two angles + * + * @param angle1 + * @param angle2 + * @return angle difference + */ + public static float getAngleDifference(float angle1, float angle2) { + return Math.abs(wrapAngle(angle1 - angle2)); + } + + /** + * Gets the angle difference between two angles + * + * @param angle1 + * @param angle2 + * @return angle difference + */ + public static double getAngleDifference(double angle1, double angle2) { + return Math.abs(wrapAngle(angle1 - angle2)); + } + + /** + * Wraps the angle to be between -180 and 180 degrees + * + * @param angle to wrap + * @return [-180 > angle >= 180] + */ + public static int wrapAngle(int angle) { + int wrappedAngle = angle; + while (wrappedAngle <= -180) { + wrappedAngle += 360; + } + while (wrappedAngle > 180) { + wrappedAngle -= 360; + } + return wrappedAngle; + } + + /** + * Wraps the angle to be between -180 and 180 degrees + * + * @param angle to wrap + * @return [-180 > angle >= 180] + */ + public static float wrapAngle(float angle) { + float wrappedAngle = angle; + while (wrappedAngle <= -180f) { + wrappedAngle += 360f; + } + while (wrappedAngle > 180f) { + wrappedAngle -= 360f; + } + return wrappedAngle; + } + + /** + * Wraps the angle to be between -180 and 180 degrees + * + * @param angle to wrap + * @return [-180 > angle >= 180] + */ + public static double wrapAngle(double angle) { + double wrappedAngle = angle; + while (wrappedAngle <= -180.0) { + wrappedAngle += 360.0; + } + while (wrappedAngle > 180.0) { + wrappedAngle -= 360.0; + } + return wrappedAngle; + } + + /** + * Normalizes a 2D-vector to be the length of another 2D-vector
    + * Calculates the normalization factor to multiply the input vector with, to + * get the requested length + * + * @param x axis of the vector + * @param z axis of the vector + * @param reqx axis of the length vector + * @param reqz axis of the length vector + * @return the normalization factor + */ + public static double normalize(double x, double z, double reqx, double reqz) { + return Math.sqrt(lengthSquared(reqx, reqz) / lengthSquared(x, z)); + } + + public static float getLookAtYaw(Entity loc, Entity lookat) { + return getLookAtYaw(loc.getLocation(), lookat.getLocation()); + } + + public static float getLookAtYaw(Block loc, Block lookat) { + return getLookAtYaw(loc.getLocation(), lookat.getLocation()); + } + + public static float getLookAtYaw(Location loc, Location lookat) { + return getLookAtYaw(lookat.getX() - loc.getX(), lookat.getZ() - loc.getZ()); + } + + public static float getLookAtYaw(Vector motion) { + return getLookAtYaw(motion.getX(), motion.getZ()); + } + + /** + * Gets the horizontal look-at angle in degrees to look into the + * 2D-direction specified + * + * @param dx axis of the direction + * @param dz axis of the direction + * @return the angle in degrees + */ + public static float getLookAtYaw(double dx, double dz) { + return atan2(dz, dx) - 180f; + } + + /** + * Gets the pitch angle in degrees to look into the direction specified + * + * @param dX axis of the direction + * @param dY axis of the direction + * @param dZ axis of the direction + * @return look-at angle in degrees + */ + public static float getLookAtPitch(double dX, double dY, double dZ) { + return getLookAtPitch(dY, length(dX, dZ)); + } + + /** + * Gets the pitch angle in degrees to look into the direction specified + * + * @param dY axis of the direction + * @param dXZ axis of the direction (length of x and z) + * @return look-at angle in degrees + */ + public static float getLookAtPitch(double dY, double dXZ) { + return -atan(dY / dXZ); + } + + /** + * Gets the inverse tangent of the value in degrees + * + * @param value + * @return inverse tangent angle in degrees + */ + public static float atan(double value) { + return (float) Math.toDegrees(CommonTrigMath.atan(value)); + } + + /** + * Gets the inverse tangent angle in degrees of the rectangle vector + * + * @param y axis + * @param x axis + * @return inverse tangent 2 angle in degrees + */ + public static float atan2(double y, double x) { + return (float) Math.toDegrees(CommonTrigMath.atan2(y, x)); + } + + /** + * Gets the floor long value from a double value + * + * @param value to get the floor of + * @return floor value + */ + public static long longFloor(double value) { + long l = (long) value; + return value < l ? l - 1L : l; + } + + /** + * Gets the floor integer value from a double value + * + * @param value to get the floor of + * @return floor value + */ + public static int floor(double value) { + int i = (int) value; + return value < (double) i ? i - 1 : i; + } + + /** + * Gets the floor integer value from a float value + * + * @param value to get the floor of + * @return floor value + */ + public static int floor(float value) { + int i = (int) value; + return value < (float) i ? i - 1 : i; + } + + /** + * Gets the ceiling integer value from a double value + * + * @param value to get the ceiling of + * @return ceiling value + */ + public static int ceil(double value) { + return -floor(-value); + } + + /** + * Gets the ceiling integer value from a float value + * + * @param value to get the ceiling of + * @return ceiling value + */ + public static int ceil(float value) { + return -floor(-value); + } + + /** + * Moves a Location into the yaw and pitch of the Location in the offset + * specified + * + * @param loc to move + * @param offset vector + * @return Translated Location + */ + public static Location move(Location loc, Vector offset) { + return move(loc, offset.getX(), offset.getY(), offset.getZ()); + } + + /** + * Moves a Location into the yaw and pitch of the Location in the offset + * specified + * + * @param loc to move + * @param dx offset + * @param dy offset + * @param dz offset + * @return Translated Location + */ + public static Location move(Location loc, double dx, double dy, double dz) { + Vector off = rotate(loc.getYaw(), loc.getPitch(), dx, dy, dz); + double x = loc.getX() + off.getX(); + double y = loc.getY() + off.getY(); + double z = loc.getZ() + off.getZ(); + return new Location(loc.getWorld(), x, y, z, loc.getYaw(), loc.getPitch()); + } + + /** + * Rotates a 3D-vector using yaw and pitch + * + * @param yaw angle in degrees + * @param pitch angle in degrees + * @param vector to rotate + * @return Vector rotated by the angle (new instance) + */ + public static Vector rotate(float yaw, float pitch, Vector vector) { + return rotate(yaw, pitch, vector.getX(), vector.getY(), vector.getZ()); + } + + /** + * Rotates a 3D-vector using yaw and pitch + * + * @param yaw angle in degrees + * @param pitch angle in degrees + * @param x axis of the vector + * @param y axis of the vector + * @param z axis of the vector + * @return Vector rotated by the angle + */ + public static Vector rotate(float yaw, float pitch, double x, double y, double z) { + // Conversions found by (a lot of) testing + double angle; + angle = Math.toRadians(yaw); + double sinyaw = Math.sin(angle); + double cosyaw = Math.cos(angle); + + angle = Math.toRadians(pitch); + double sinpitch = Math.sin(angle); + double cospitch = Math.cos(angle); + + Vector vector = new Vector(); + vector.setX((x * sinyaw) - (y * cosyaw * sinpitch) - (z * cosyaw * cospitch)); + vector.setY((y * cospitch) - (z * sinpitch)); + vector.setZ(-(x * cosyaw) - (y * sinyaw * sinpitch) - (z * sinyaw * cospitch)); + return vector; + } + + /** + * Returns the floor modulus of the int arguments + * + * @param x the dividend + * @param y the divisor + * @returnthe floor modulus x + */ + public static int floorMod(int x, int y) { + return Math.floorMod(x, y); + } + + public static double floorMod(double x, double y){ + return (x - Math.floor(x/y) * y); + } + + public static float floorMod(float x, float y){ + return (x - (float)Math.floor(x/y) * y); + } + + /** + * Returns the floor modulus of the long arguments + * + * @param x the dividend + * @param y the divisor + * @returnthe floor modulus x + */ + public static long floorMod(long x, long y) { + return Math.floorMod(x, y); + } + + /** + * Returns the floor division of the int arguments + * @param x the dividend + * @param y the divisor + * @return floor division x + */ + public static int floorDiv(int x, int y) { + return Math.floorDiv(x, y); + } + + /** + * Returns the floor division of the long arguments + * @param x the dividend + * @param y the divisor + * @return floor division x + */ + public static long floorDiv(long x, long y) { + return Math.floorDiv(x, y); + } + + /** + * Rounds the specified value to the amount of decimals specified + * + * @param value to round + * @param decimals count + * @return value round to the decimal count specified + */ + public static double round(double value, int decimals) { + double p = Math.pow(10, decimals); + return Math.round(value * p) / p; + } + + /** + * Returns 0 if the value is not-a-number + * + * @param value to check + * @return The value, or 0 if it is NaN + */ + public static double fixNaN(double value) { + return fixNaN(value, 0.0); + } + + /** + * Returns 0 if the value is not-a-number + * + * @param value to check + * @return The value, or 0 if it is NaN + */ + public static float fixNaN(float value) { + return fixNaN(value, 0.0f); + } + + /** + * Returns the default if the value is not-a-number + * + * @param value to check + * @param def value + * @return The value, or the default if it is NaN + */ + public static double fixNaN(double value, double def) { + return Double.isNaN(value) ? def : value; + } + + /** + * Returns the default if the value is not-a-number + * + * @param value to check + * @param def value + * @return The value, or the default if it is NaN + */ + public static float fixNaN(float value, float def) { + return Float.isNaN(value) ? def : value; + } + + /** + * Converts a location value into a chunk coordinate + * + * @param loc to convert + * @return chunk coordinate + */ + public static int toChunk(double loc) { + return floor(loc / (double) CHUNK_VALUES); + } + + /** + * Converts a location value into a chunk coordinate + * + * @param loc to convert + * @return chunk coordinate + */ + public static int toChunk(int loc) { + return loc >> CHUNK_BITS; + } + + public static double useOld(double oldvalue, double newvalue, double peruseold) { + return oldvalue + (peruseold * (newvalue - oldvalue)); + } + + public static double lerp(double d1, double d2, double stage) { + if (Double.isNaN(stage) || stage > 1) { + return d2; + } else if (stage < 0) { + return d1; + } else { + return d1 * (1 - stage) + d2 * stage; + } + } + + public static Vector lerp(Vector vec1, Vector vec2, double stage) { + Vector newvec = new Vector(); + newvec.setX(lerp(vec1.getX(), vec2.getX(), stage)); + newvec.setY(lerp(vec1.getY(), vec2.getY(), stage)); + newvec.setZ(lerp(vec1.getZ(), vec2.getZ(), stage)); + return newvec; + } + + public static Location lerp(Location loc1, Location loc2, double stage) { + Location newloc = new Location(loc1.getWorld(), 0, 0, 0); + newloc.setX(lerp(loc1.getX(), loc2.getX(), stage)); + newloc.setY(lerp(loc1.getY(), loc2.getY(), stage)); + newloc.setZ(lerp(loc1.getZ(), loc2.getZ(), stage)); + newloc.setYaw((float) lerp(loc1.getYaw(), loc2.getYaw(), stage)); + newloc.setPitch((float) lerp(loc1.getPitch(), loc2.getPitch(), stage)); + return newloc; + } + + /** + * Checks whether one value is negative and the other positive, or opposite + * + * @param value1 to check + * @param value2 to check + * @return True if value1 is inverted from value2 + */ + public static boolean isInverted(double value1, double value2) { + return (value1 > 0 && value2 < 0) || (value1 < 0 && value2 > 0); + } + + /** + * Gets the direction of yaw and pitch angles + * + * @param yaw angle in degrees + * @param pitch angle in degrees + * @return Direction Vector + */ + public static Vector getDirection(float yaw, float pitch) { + Vector vector = new Vector(); + double rotX = Math.toRadians(yaw); + double rotY = Math.toRadians(pitch); + vector.setY(-Math.sin(rotY)); + double h = Math.cos(rotY); + vector.setX(-h * Math.sin(rotX)); + vector.setZ(h * Math.cos(rotX)); + return vector; + } + + /** + * Clamps the value between -limit and limit + * + * @param value to clamp + * @param limit + * @return value, -limit or limit + */ + public static double clamp(double value, double limit) { + return clamp(value, -limit, limit); + } + + /** + * Clamps the value between the min and max values + * + * @param value to clamp + * @param min + * @param max + * @return value, min or max + */ + public static double clamp(double value, double min, double max) { + return value < min ? min : (Math.min(value, max)); + } + + /** + * Clamps the value between -limit and limit + * + * @param value to clamp + * @param limit + * @return value, -limit or limit + */ + public static float clamp(float value, float limit) { + return clamp(value, -limit, limit); + } + + /** + * Clamps the value between the min and max values + * + * @param value to clamp + * @param min + * @param max + * @return value, min or max + */ + public static float clamp(float value, float min, float max) { + return value < min ? min : (Math.min(value, max)); + } + + /** + * Clamps the value between -limit and limit + * + * @param value to clamp + * @param limit + * @return value, -limit or limit + */ + public static int clamp(int value, int limit) { + return clamp(value, -limit, limit); + } + + /** + * Clamps the value between the min and max values + * + * @param value to clamp + * @param min + * @param max + * @return value, min or max + */ + public static int clamp(int value, int min, int max) { + return value < min ? min : (Math.min(value, max)); + } + + /** + * Clamps the value between -limit and limit + * + * @param value to clamp + * @param limit + * @return value, -limit or limit + */ + public static long clamp(long value, long limit) { + return clamp(value, -limit, limit); + } + + /** + * Clamps the value between the min and max values + * + * @param value to clamp + * @param min + * @param max + * @return value, min or max + */ + public static long clamp(long value, long min, long max) { + return value < min ? min : (Math.min(value, max)); + } + + /** + * Turns a value negative or keeps it positive based on a boolean input + * + * @param value to work with + * @param negative - True to invert, False to keep the old value + * @return the value or inverted (-value) + */ + public static int invert(int value, boolean negative) { + return negative ? -value : value; + } + + /** + * Turns a value negative or keeps it positive based on a boolean input + * + * @param value to work with + * @param negative - True to invert, False to keep the old value + * @return the value or inverted (-value) + */ + public static float invert(float value, boolean negative) { + return negative ? -value : value; + } + + /** + * Turns a value negative or keeps it positive based on a boolean input + * + * @param value to work with + * @param negative - True to invert, False to keep the old value + * @return the value or inverted (-value) + */ + public static double invert(double value, boolean negative) { + return negative ? -value : value; + } + + /** + * Merges two ints into a long + * + * @param msw integer + * @param lsw integer + * @return merged long value + */ + public static long toLong(int msw, int lsw) { + return ((long) msw << 32) + lsw - Integer.MIN_VALUE; + } + + public static long longHashToLong(int msw, int lsw) { + return ((long) msw << 32) + lsw - Integer.MIN_VALUE; + } + + public static int longHashMsw(long key) { + return (int) (key >> 32); + } + + public static int longHashLsw(long key) { + return (int) (key) + Integer.MIN_VALUE; + } + + /** + * Takes the most and least significant words of both keys, sums them together, + * and produces a new key with the two words summed. + * + * @param keyA + * @param keyB + * @return words of keyA and keyB summed, and turned back into a long + */ + public static long longHashSumW(long keyA, long keyB) { + long sum_msw = (keyA & 0xFFFFFFFF00000000L) + (keyB & 0xFFFFFFFF00000000L); + long sum_lsw = (keyA) + (keyB); + return sum_msw + (int) sum_lsw - Integer.MIN_VALUE; + } + + /** + * Shorthand equivalent of:
    + * longHashToLong(longHashMsw(a)+longHashMsw(b), longHashLsw(a)+longHashLsw(b)) + * + * @param key_a + * @param key_b + * @return key_a + key_b + */ + public static long longHashAdd(long key_a, long key_b) { + return key_a + key_b + Integer.MIN_VALUE; + } + + public static void setVectorLength(Vector vector, double length) { + setVectorLengthSquared(vector, Math.signum(length) * length * length); + } + + public static void setVectorLengthSquared(Vector vector, double lengthsquared) { + double vlength = vector.lengthSquared(); + if (Math.abs(vlength) > 0.0001) { + if (lengthsquared < 0) { + vector.multiply(-Math.sqrt(-lengthsquared / vlength)); + } else { + vector.multiply(Math.sqrt(lengthsquared / vlength)); + } + } + } + + public static boolean isHeadingTo(BlockFace direction, Vector velocity) { + return isHeadingTo(FaceUtil.faceToVector(direction), velocity); + } + + public static boolean isHeadingTo(Location from, Location to, Vector velocity) { + return isHeadingTo(new Vector(to.getX() - from.getX(), to.getY() - from.getY(), to.getZ() - from.getZ()), velocity); + } + + public static boolean isHeadingTo(Vector offset, Vector velocity) { + double dbefore = offset.lengthSquared(); + if (dbefore < 0.0001) { + return true; + } + Vector clonedVelocity = velocity.clone(); + setVectorLengthSquared(clonedVelocity, dbefore); + return dbefore > clonedVelocity.subtract(offset).lengthSquared(); + } + + /** + * Calculates the normalization factor for a 3D vector. + * Multiplying the input vector with this factor will turn it into a vector of unit length. + * If the input vector is (0,0,0), Infinity is returned. + * + * @param v + * @return normalization factor + */ + public static double getNormalizationFactor(Vector v) { + return getNormalizationFactorLS(v.lengthSquared()); + } + + /** + * Calculates the normalization factor for a 4D vector. + * Multiplying the input vector with this factor will turn it into a vector of unit length. + * If the input vector is (0,0,0,0), Infinity is returned. + * + * @param x + * @param y + * @param z + * @param w + * @return normalization factor + */ + public static double getNormalizationFactor(double x, double y, double z, double w) { + return getNormalizationFactorLS(x * x + y * y + z * z + w * w); + } + + /** + * Calculates the normalization factor for a 3D vector. + * Multiplying the input vector with this factor will turn it into a vector of unit length. + * If the input vector is (0,0,0), Infinity is returned. + * + * @param x + * @param y + * @param z + * @return normalization factor + */ + public static double getNormalizationFactor(double x, double y, double z) { + return getNormalizationFactorLS(x * x + y * y + z * z); + } + + /** + * Calculates the normalization factor for a 2D vector. + * Multiplying the input vector with this factor will turn it into a vector of unit length. + * If the input vector is (0,0), Infinity is returned. + * + * @param x + * @param y + * @return normalization factor + */ + public static double getNormalizationFactor(double x, double y) { + return getNormalizationFactorLS(x * x + y * y); + } + + /** + * Calculates the normalization factor for a squared length. + * Multiplying the input values with this factor will turn it into a vector of unit length. + * If the squared length is 0, Infinity is returned. + * + * @param lengthSquared + * @return normalization factor + */ + public static double getNormalizationFactorLS(double lengthSquared) { + // https://stackoverflow.com/a/12934750 + if (Math.abs(1.0 - lengthSquared) < 2.107342e-08) { + return (2.0 / (1.0 + lengthSquared)); + } else { + return 1.0 / Math.sqrt(lengthSquared); + } + } + + /** + * Calculates the angle difference between two vectors in degrees + * + * @param v0 first vector + * @param v1 second vector + * @return absolute angle difference in degrees + */ + public static double getAngleDifference(Vector v0, Vector v1) { + double dot = v0.dot(v1); + dot *= MathUtil.getNormalizationFactor(v0); + dot *= MathUtil.getNormalizationFactor(v1); + return Math.toDegrees(Math.acos(dot)); + } + + /** + * Sets the x, y and z coordinates of a Bukkit Vector + * + * @param vector The vector to update + * @param value The value to set vector to + * @return input vector + */ + public static Vector setVector(Vector vector, Vector value) { + return vector.copy(value); + } + + /** + * Sets the x, y and z coordinates of a Bukkit Vector + * + * @param vector The vector to update + * @param x The new x-coordinate to set in vector + * @param y The new y-coordinate to set in vector + * @param z The new z-coordinate to set in vector + * @return input vector + */ + public static Vector setVector(Vector vector, double x, double y, double z) { + vector.setX(x); + vector.setY(y); + vector.setZ(z); + return vector; + } + + /** + * Adds the x, y and z coordinate values to the original coordinates of a vector. + * The input vector is updated. + * + * @param vector The vector to update + * @param ax The value to add to the x-coordinate + * @param ay The value to add to the y-coordinate + * @param az The value to add to the z-coordinate + * @return input vector + */ + public static Vector addToVector(Vector vector, double ax, double ay, double az) { + vector.setX(vector.getX() + ax); + vector.setY(vector.getY() + ay); + vector.setZ(vector.getZ() + az); + return vector; + } + + /** + * Subtracts the x, y and z coordinate values from the original coordinates of a vector. + * The input vector is updated. + * + * @param vector The vector to update + * @param sx The value to subtract from the x-coordinate + * @param sy The value to subtract from the y-coordinate + * @param sz The value to subtract from the z-coordinate + * @return input vector + */ + public static Vector subtractFromVector(Vector vector, double sx, double sy, double sz) { + vector.setX(vector.getX() - sx); + vector.setY(vector.getY() - sy); + vector.setZ(vector.getZ() - sz); + return vector; + } + + /** + * Multiplies the x, y and z coordinate values of the original coordinates of a vector. + * The input vector is updated. + * + * @param vector The vector to update + * @param mx The value to multiply the x-coordinate with + * @param my The value to multiply the y-coordinate with + * @param mz The value to multiply the z-coordinate with + * @return input vector + */ + public static Vector multiplyVector(Vector vector, double mx, double my, double mz) { + vector.setX(vector.getX() * mx); + vector.setY(vector.getY() * my); + vector.setZ(vector.getZ() * mz); + return vector; + } + + /** + * Divides the x, y and z coordinate values of the original coordinates of a vector. + * The input vector is updated. + * + * @param vector The vector to update + * @param mx The value to divide the x-coordinate with + * @param my The value to divide the y-coordinate with + * @param mz The value to divide the z-coordinate with + * @return input vector + */ + public static Vector divideVector(Vector vector, double mx, double my, double mz) { + vector.setX(vector.getX() / mx); + vector.setY(vector.getY() / my); + vector.setZ(vector.getZ() / mz); + return vector; + } + + public static double map(double x, double inMin, double inMax, double outMin, double outMax){ + return (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/math/Matrix4x4.java b/src/main/java/com/jverbruggen/jrides/models/math/Matrix4x4.java new file mode 100644 index 00000000..848c3918 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/math/Matrix4x4.java @@ -0,0 +1,965 @@ +/** + * This code has been kindly borrowed from bergerkiller's BKCommonLib + * + * MIT License + * + * Copyright (C) 2013-2015 bergerkiller Copyright (C) 2016-2020 Berger Healer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, and/or sublicense the Software, + * and to permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.jverbruggen.jrides.models.math; + +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.util.Vector; + +public class Matrix4x4 implements Cloneable { + public double m00, m01, m02, m03; + public double m10, m11, m12, m13; + public double m20, m21, m22, m23; + public double m30, m31, m32, m33; + + /** + * Constructs a new 4x4 matrix, initialized as an identity matrix: + *
    +     * 1 0 0 0
    +     * 0 1 0 0
    +     * 0 0 1 0
    +     * 0 0 0 1
    +     * 
    + */ + public Matrix4x4() { + this.setIdentity(); + } + + /** + * Constructs a new 4x4 matrix using the 16 values specified + */ + public Matrix4x4( + double m00, double m01, double m02, double m03, + double m10, double m11, double m12, double m13, + double m20, double m21, double m22, double m23, + double m30, double m31, double m32, double m33) + { + this.set( + m00, m01, m02, m03, + m10, m11, m12, m13, + m20, m21, m22, m23, + m30, m31, m32, m33 + ); + } + + /** + * Constructs a new 4x4 matrix, copying the 16 values from another matrix + * + * @param matrix to set to + */ + public Matrix4x4(Matrix4x4 matrix) { + this.set(matrix); + } + + /** + * Sets all 16 values of this 4x4 matrix + */ + public final void set( + double m00, double m01, double m02, double m03, + double m10, double m11, double m12, double m13, + double m20, double m21, double m22, double m23, + double m30, double m31, double m32, double m33) + { + this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; + this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; + this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23; + this.m30 = m30; this.m31 = m31; this.m32 = m32; this.m33 = m33; + } + + /** + * Sets this matrix to all values of another 4x4 matrix + * + * @param m matrix to set to + */ + public final void set(Matrix4x4 m) { + this.set( + m.m00, m.m01, m.m02, m.m03, + m.m10, m.m11, m.m12, m.m13, + m.m20, m.m21, m.m22, m.m23, + m.m30, m.m31, m.m32, m.m33 + ); + } + + /** + * Sets this matrix to the identity matrix:
    + *
    +     * 1 0 0 0
    +     * 0 1 0 0
    +     * 0 0 1 0
    +     * 0 0 0 1
    +     * 
    + */ + public final void setIdentity() + { + this.set( + 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0 + ); + } + + /** + * Sets this matrix to all the values in an array + * + * @param values to set to (length 16 or less) + */ + public final void set(float[] values) { + this.set( + values[0], values[1], values[2], values[3], + values[4], values[5], values[6], values[7], + values[8], values[9], values[10], values[11], + values[12], values[13], values[14], values[15] + ); + } + + /** + * Sets this matrix to all the values in an array + * + * @param values array to read from (length 16 or more) + */ + public final void set(double[] values) { + this.set( + values[0], values[1], values[2], values[3], + values[4], values[5], values[6], values[7], + values[8], values[9], values[10], values[11], + values[12], values[13], values[14], values[15] + ); + } + + /** + * Gets all 16 values from this 4x4 matrix and writes them to an array + * + * @param values array to write to (length 16 or more) + */ + public final void toArray(float[] values) { + values[0] = (float) m00; values[1] = (float) m01; values[2] = (float) m02; values[3] = (float) m03; + values[4] = (float) m10; values[5] = (float) m11; values[6] = (float) m12; values[7] = (float) m13; + values[8] = (float) m20; values[9] = (float) m21; values[10] = (float) m22; values[11] = (float) m23; + values[12] = (float) m30; values[13] = (float) m31; values[14] = (float) m32; values[15] = (float) m33; + } + + /** + * Gets all 16 values from this 4x4 matrix and writes them to an array + * + * @param values array to write to (length 16 or more) + */ + public final void toArray(double[] values) { + values[0] = m00; values[1] = m01; values[2] = m02; values[3] = m03; + values[4] = m10; values[5] = m11; values[6] = m12; values[7] = m13; + values[8] = m20; values[9] = m21; values[10] = m22; values[11] = m23; + values[12] = m30; values[13] = m31; values[14] = m32; values[15] = m33; + } + + /** + * General invert routine. Inverts m1 and places the result in "this". + * Note that this routine handles both the "this" version and the + * non-"this" version. + * + * Also note that since this routine is slow anyway, we won't worry + * about allocating a little bit of garbage. + */ + public final boolean invert() { + // Copy source matrix to t1tmp + double[] mInput = new double[16]; + int[] row_perm = new int[4]; + this.toArray(mInput); + if (!MatrixMath.luDecomposition(mInput, row_perm)) { + // Matrix has no inverse + return false; + } + + // Perform back substitution on the identity matrix + double[] mOutput = new double[16]; + for(int i=0;i<16;i++) mOutput[i] = 0.0; + mOutput[0] = 1.0; mOutput[5] = 1.0; mOutput[10] = 1.0; mOutput[15] = 1.0; + MatrixMath.luBacksubstitution(mInput, row_perm, mOutput); + this.set(mOutput); + return true; + } + + /** + * Multiplies this matrix with a rotation transformation defined in a Quaternion + * + * @param quat to rotate with + */ + public final void rotate(Quaternion quat) { + double x = quat.getX(); + double y = quat.getY(); + double z = quat.getZ(); + double w = quat.getW(); + + double q00 = 2.0 * (-y*y + -z*z); + double q01 = 2.0 * ( x*y + -z*w); + double q02 = 2.0 * ( x*z + y*w); + double q10 = 2.0 * ( x*y + z*w); + double q11 = 2.0 * (-x*x + -z*z); + double q12 = 2.0 * ( y*z + -x*w); + double q20 = 2.0 * ( x*z + -y*w); + double q21 = 2.0 * ( y*z + x*w); + double q22 = 2.0 * (-x*x + -y*y); + + double a00, a01, a02; + double a10, a11, a12; + double a20, a21, a22; + double a30, a31, a32; + + a00 = this.m00*q00 + this.m01*q10 + this.m02*q20; + a01 = this.m00*q01 + this.m01*q11 + this.m02*q21; + a02 = this.m00*q02 + this.m01*q12 + this.m02*q22; + + a10 = this.m10*q00 + this.m11*q10 + this.m12*q20; + a11 = this.m10*q01 + this.m11*q11 + this.m12*q21; + a12 = this.m10*q02 + this.m11*q12 + this.m12*q22; + + a20 = this.m20*q00 + this.m21*q10 + this.m22*q20; + a21 = this.m20*q01 + this.m21*q11 + this.m22*q21; + a22 = this.m20*q02 + this.m21*q12 + this.m22*q22; + + a30 = this.m30*q00 + this.m31*q10 + this.m32*q20; + a31 = this.m30*q01 + this.m31*q11 + this.m32*q21; + a32 = this.m30*q02 + this.m31*q12 + this.m32*q22; + + this.m00 += a00; this.m01 += a01; this.m02 += a02; + this.m10 += a10; this.m11 += a11; this.m12 += a12; + this.m20 += a20; this.m21 += a21; this.m22 += a22; + this.m30 += a30; this.m31 += a31; this.m32 += a32; + } + + /** + * Multiplies this matrix with a rotation transformation about the X-axis + * + * @param angle the angle to rotate about the X axis in degrees + */ + public final void rotateX(double angle) { + if (angle != 0.0) { + double angleRad = Math.toRadians(angle); + rotateX_unsafe(Math.cos(angleRad), Math.sin(angleRad)); + } + } + + /** + * Multiplies this matrix with a rotation transformation about the X-axis. + * Instead of a single angle, the y and z of the rotated vector can be specified. + * + * @param y + * @param z + */ + public final void rotateX(double y, double z) { + double f = MathUtil.getNormalizationFactor(y, z); + rotateX_unsafe(y * f, z * f); + } + + private void rotateX_unsafe(double cos, double sin) { + double m01, m02; + double m11, m12; + double m21, m22; + double m31, m32; + + m01 = this.m01*cos + this.m02*sin; + m02 = this.m01*(-sin) + this.m02*cos; + + m11 = this.m11*cos + this.m12*sin; + m12 = this.m11*(-sin) + this.m12*cos; + + m21 = this.m21*cos + this.m22*sin; + m22 = this.m21*(-sin) + this.m22*cos; + + m31 = this.m31*cos + this.m32*sin; + m32 = this.m31*(-sin) + this.m32*cos; + + this.m01 = m01; this.m02 = m02; + this.m11 = m11; this.m12 = m12; + this.m21 = m21; this.m22 = m22; + this.m31 = m31; this.m32 = m32; + } + + /** + * Multiplies this matrix with a rotation transformation about the Y-axis + * + * @param angle the angle to rotate about the Y axis in degrees + */ + public final void rotateY(double angle) { + if (angle != 0.0) { + double angleRad = Math.toRadians(angle); + rotateY_unsafe(Math.cos(angleRad), Math.sin(angleRad)); + } + } + + /** + * Multiplies this matrix with a rotation transformation about the Y-axis. + * Instead of a single angle, the x and z of the rotated vector can be specified. + * + * @param x + * @param z + */ + public final void rotateY(double x, double z) { + double f = MathUtil.getNormalizationFactor(x, z); + rotateY_unsafe(x * f, z * f); + } + + private void rotateY_unsafe(double cos, double sin) { + double m00, m02; + double m10, m12; + double m20, m22; + double m30, m32; + + m00 = this.m00*cos + this.m02*(-sin); + m02 = this.m00*sin + this.m02*cos; + + m10 = this.m10*cos + this.m12*(-sin); + m12 = this.m10*sin + this.m12*cos; + + m20 = this.m20*cos + this.m22*(-sin); + m22 = this.m20*sin + this.m22*cos; + + m30 = this.m30*cos + this.m32*(-sin); + m32 = this.m30*sin + this.m32*cos; + + this.m00 = m00; this.m02 = m02; + this.m10 = m10; this.m12 = m12; + this.m20 = m20; this.m22 = m22; + this.m30 = m30; this.m32 = m32; + } + + /** + * Multiplies this matrix with a rotation transformation about the Z-axis + * + * @param angle the angle to rotate about the Z axis in degrees + */ + public final void rotateZ(double angle) { + if (angle != 0.0) { + double angleRad = Math.toRadians(angle); + rotateZ_unsafe(Math.cos(angleRad), Math.sin(angleRad)); + } + } + + /** + * Multiplies this matrix with a rotation transformation about the Z-axis. + * Instead of a single angle, the x and y of the rotated vector can be specified. + * + * @param x + * @param y + */ + public final void rotateZ(double x, double y) { + double f = MathUtil.getNormalizationFactor(x, y); + rotateZ_unsafe(x * f, y * f); + } + + private void rotateZ_unsafe(double cos, double sin) { + double m00, m01; + double m10, m11; + double m20, m21; + double m30, m31; + + m00 = this.m00*cos + this.m01*sin; + m01 = this.m00*(-sin) + this.m01*cos; + + m10 = this.m10*cos + this.m11*sin; + m11 = this.m10*(-sin) + this.m11*cos; + + m20 = this.m20*cos + this.m21*sin; + m21 = this.m20*(-sin) + this.m21*cos; + + m30 = this.m30*cos + this.m31*sin; + m31 = this.m30*(-sin) + this.m31*cos; + + this.m00 = m00; this.m01 = m01; + this.m10 = m10; this.m11 = m11; + this.m20 = m20; this.m21 = m21; + this.m30 = m30; this.m31 = m31; + } + + /** + * Multiplies this matrix with a rotation transformation in yaw/pitch/roll, based on the Minecraft + * coordinate system. This will differ slightly from the standard rotateX/Y/Z functions. + * + * @param rotation (x=pitch, y=yaw, z=roll) + */ + public final void rotateYawPitchRoll(Vector3 rotation) { + rotateYawPitchRoll(rotation.x, rotation.y, rotation.z); + } + + /** + * Multiplies this matrix with a rotation transformation in yaw/pitch/roll, based on the Minecraft + * coordinate system. This will differ slightly from the standard rotateX/Y/Z functions. + * + * @param rotation (x=pitch, y=yaw, z=roll) + */ + public final void rotateYawPitchRoll(Vector rotation) { + rotateYawPitchRoll(rotation.getX(), rotation.getY(), rotation.getZ()); + } + + /** + * Multiplies this matrix with a rotation transformation in yaw/pitch/roll, based on the Minecraft + * coordinate system. This will differ slightly from the standard rotateX/Y/Z functions. + * + * @param pitch rotation (X) + * @param yaw rotation (Y) + * @param roll rotation (Z) + */ + public final void rotateYawPitchRoll(double pitch, double yaw, double roll) { + this.rotateY(-yaw); + this.rotateX(pitch); + this.rotateZ(roll); + } + + /** + * Multiplies this matrix with a rotation transformation in yaw/pitch/roll, based on the Minecraft + * coordinate system. This will differ slightly from the standard rotateX/Y/Z functions. + * + * @param pitch rotation (X) + * @param yaw rotation (Y) + * @param roll rotation (Z) + */ + public final void rotateYawPitchRoll(float pitch, float yaw, float roll) { + this.rotateY(-yaw); + this.rotateX(pitch); + this.rotateZ(roll); + } + + /** + * Gets the rotation transformation performed as a Quaternion + * + * @return rotation quaternion + */ + public final Quaternion getRotation() { + double tr = m00 + m11 + m22; + if (tr > 0) { + return new Quaternion(m21-m12, m02-m20, m10-m01, 1.0 + tr); + } else if ((m00 > m11) & (m00 > m22)) { + return new Quaternion(1.0+m00-m11-m22, m01+m10, m02+m20, m21-m12); + } else if (m11 > m22) { + return new Quaternion(m01+m10, 1.0+m11-m00-m22, m12+m21, m02-m20); + } else { + return new Quaternion(m02+m20, m12+m21, 1.0+m22-m00-m11, m10-m01); + } + } + + /** + * Deduces the pitch component (x) of {@link #getYawPitchRoll()} + * + * @return pitch + */ + public final double getRotationPitch() { + /* == This portion is repeated and copied from getRotation() == */ + double x, y, z, w, tr = m00 + m11 + m22; + if (tr > 0) { + x = m21-m12; y = m02-m20; z = m10-m01; w = 1.0 + tr; + } else if ((m00 > m11) && (m00 > m22)) { + x = 1.0+m00-m11-m22; y = m01+m10; z = m02+m20; w = m21-m12; + } else if (m11 > m22) { + x = m01+m10; y = 1.0+m11-m00-m22; z = m12+m21; w = m02-m20; + } else { + x = m02+m20; y = m12+m21; z = 1.0+m22-m00-m11; w = m10-m01; + } + double f = MathUtil.getNormalizationFactor(x, y, z, w); + x *= f; y *= f; z *= f; w *= f; + /* ============================================================ */ + + return Quaternion.getPitch(x, y, z, w); + } + + /** + * Deduces the yaw component (y) of {@link #getYawPitchRoll()} + * + * @return yaw + */ + public final double getRotationYaw() { + /* == This portion is repeated and copied from getRotation() == */ + double x, y, z, w, tr = m00 + m11 + m22; + if (tr > 0) { + x = m21-m12; y = m02-m20; z = m10-m01; w = 1.0 + tr; + } else if ((m00 > m11) && (m00 > m22)) { + x = 1.0+m00-m11-m22; y = m01+m10; z = m02+m20; w = m21-m12; + } else if (m11 > m22) { + x = m01+m10; y = 1.0+m11-m00-m22; z = m12+m21; w = m02-m20; + } else { + x = m02+m20; y = m12+m21; z = 1.0+m22-m00-m11; w = m10-m01; + } + double f = MathUtil.getNormalizationFactor(x, y, z, w); + x *= f; y *= f; z *= f; w *= f; + /* ============================================================ */ + + return Quaternion.getYaw(x, y, z, w); + } + + /** + * Deduces the roll component (z) of {@link #getYawPitchRoll()} + * + * @return roll + */ + public final double getRotationRoll() { + /* == This portion is repeated and copied from getRotation() == */ + double x, y, z, w, tr = m00 + m11 + m22; + if (tr > 0) { + x = m21-m12; y = m02-m20; z = m10-m01; w = 1.0 + tr; + } else if ((m00 > m11) && (m00 > m22)) { + x = 1.0+m00-m11-m22; y = m01+m10; z = m02+m20; w = m21-m12; + } else if (m11 > m22) { + x = m01+m10; y = 1.0+m11-m00-m22; z = m12+m21; w = m02-m20; + } else { + x = m02+m20; y = m12+m21; z = 1.0+m22-m00-m11; w = m10-m01; + } + double f = MathUtil.getNormalizationFactor(x, y, z, w); + x *= f; y *= f; z *= f; w *= f; + /* ============================================================ */ + + return Quaternion.getRoll(x, y, z, w); + } + + /** + * Deduces the yaw/pitch/roll values in degrees that this matrix transforms objects with + * + * @return axis rotations: {x=pitch, y=yaw, z=roll} + */ + public final Vector getYawPitchRoll() { + /* == This portion is repeated and copied from getRotation() == */ + double x, y, z, w, tr = m00 + m11 + m22; + if (tr > 0) { + x = m21-m12; y = m02-m20; z = m10-m01; w = 1.0 + tr; + } else if ((m00 > m11) && (m00 > m22)) { + x = 1.0+m00-m11-m22; y = m01+m10; z = m02+m20; w = m21-m12; + } else if (m11 > m22) { + x = m01+m10; y = 1.0+m11-m00-m22; z = m12+m21; w = m02-m20; + } else { + x = m02+m20; y = m12+m21; z = 1.0+m22-m00-m11; w = m10-m01; + } + double f = MathUtil.getNormalizationFactor(x, y, z, w); + x *= f; y *= f; z *= f; w *= f; + /* ============================================================ */ + + return Quaternion.getYawPitchRoll(x, y, z, w); + } + + /** + * Multiplies this matrix with a translation transformation + * + * @param translation + */ + public final void translate(Vector3 translation) { + this.translate(translation.x, translation.y, translation.z); + } + + /** + * Multiplies this matrix with a translation transformation + * + * @param dx translation + * @param dy translation + * @param dz translation + */ + public final void translate(double dx, double dy, double dz) { + this.m03 += this.m00*dx + this.m01*dy + this.m02*dz; + this.m13 += this.m10*dx + this.m11*dy + this.m12*dz; + this.m23 += this.m20*dx + this.m21*dy + this.m22*dz; + this.m33 += this.m30*dx + this.m31*dy + this.m32*dz; + } + + /** + * Multiplies this matrix with a translation transformation. + * + * @param translation + */ + public final void translate(Vector translation) { + this.translate(translation.getX(), translation.getY(), translation.getZ()); + } + + /** + * Multiplies this matrix with a scale transformation + * + * @param scale + */ + public final void scale(Vector3 scale) { + this.scale(scale.x, scale.y, scale.z); + } + + /** + * Multiplies this matrix with a scale transformation + * + * @param sx scale + * @param sy scale + * @param sz scale + */ + public final void scale(double sx, double sy, double sz) { + this.m00 *= sx; this.m10 *= sx; this.m20 *= sx; this.m30 *= sx; + this.m01 *= sy; this.m11 *= sy; this.m21 *= sy; this.m31 *= sy; + this.m02 *= sz; this.m12 *= sz; this.m22 *= sz; this.m32 *= sz; + } + + /** + * Multiplies this matrix with a scale transformation + * + * @param scale + */ + public final void scale(double scale) { + this.scale(scale, scale, scale); + } + + /** + * Translates and rotates this Matrix with the position information of a Bukkit Location + * + * @param location to translate and rotate by + */ + public final void translateRotate(Location location) { + this.translateRotate(location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); + } + + /** + * Translates and rotates this Matrix with position and rotation information + * + * @param x position + * @param y position + * @param z position + * @param pitch rotation (X) + * @param yaw rotation (Y) + */ + public final void translateRotate(double x, double y, double z, float pitch, float yaw) { + this.translate(x, y, z); + this.rotateYawPitchRoll(pitch, yaw, 0.0f); + } + + /** + * Translates and rotates this Matrix with position and rotation information + * + * @param x position + * @param y position + * @param z position + * @param pitch rotation (X) + * @param yaw rotation (Y) + * @param roll rotation (Z) + */ + public final void translateRotate(double x, double y, double z, float pitch, float yaw, float roll) { + this.translate(x, y, z); + this.rotateYawPitchRoll(pitch, yaw, roll); + } + + /** + * Multiplies this matrix with another, storing the result in this matrix + * + * @param mRight the right-hand side matrix to multiply with + */ + public final void multiply(Matrix4x4 mRight) { + multiply(this, mRight, this); + } + + /** + * Stores the result of a matrix multiplication in this matrix. + * One of the input matrices is allowed to be the same instance as this matrix. + * + * @param mLeft Left side of the matrix multiplication + * @param mRight Right side of the matrix multiplication + */ + public final void storeMultiply(Matrix4x4 mLeft, Matrix4x4 mRight) { + double m00, m01, m02, m03; + double m10, m11, m12, m13; + double m20, m21, m22, m23; + double m30, m31, m32, m33; + + m00 = mLeft.m00*mRight.m00 + mLeft.m01*mRight.m10 + + mLeft.m02*mRight.m20 + mLeft.m03*mRight.m30; + m01 = mLeft.m00*mRight.m01 + mLeft.m01*mRight.m11 + + mLeft.m02*mRight.m21 + mLeft.m03*mRight.m31; + m02 = mLeft.m00*mRight.m02 + mLeft.m01*mRight.m12 + + mLeft.m02*mRight.m22 + mLeft.m03*mRight.m32; + m03 = mLeft.m00*mRight.m03 + mLeft.m01*mRight.m13 + + mLeft.m02*mRight.m23 + mLeft.m03*mRight.m33; + + m10 = mLeft.m10*mRight.m00 + mLeft.m11*mRight.m10 + + mLeft.m12*mRight.m20 + mLeft.m13*mRight.m30; + m11 = mLeft.m10*mRight.m01 + mLeft.m11*mRight.m11 + + mLeft.m12*mRight.m21 + mLeft.m13*mRight.m31; + m12 = mLeft.m10*mRight.m02 + mLeft.m11*mRight.m12 + + mLeft.m12*mRight.m22 + mLeft.m13*mRight.m32; + m13 = mLeft.m10*mRight.m03 + mLeft.m11*mRight.m13 + + mLeft.m12*mRight.m23 + mLeft.m13*mRight.m33; + + m20 = mLeft.m20*mRight.m00 + mLeft.m21*mRight.m10 + + mLeft.m22*mRight.m20 + mLeft.m23*mRight.m30; + m21 = mLeft.m20*mRight.m01 + mLeft.m21*mRight.m11 + + mLeft.m22*mRight.m21 + mLeft.m23*mRight.m31; + m22 = mLeft.m20*mRight.m02 + mLeft.m21*mRight.m12 + + mLeft.m22*mRight.m22 + mLeft.m23*mRight.m32; + m23 = mLeft.m20*mRight.m03 + mLeft.m21*mRight.m13 + + mLeft.m22*mRight.m23 + mLeft.m23*mRight.m33; + + m30 = mLeft.m30*mRight.m00 + mLeft.m31*mRight.m10 + + mLeft.m32*mRight.m20 + mLeft.m33*mRight.m30; + m31 = mLeft.m30*mRight.m01 + mLeft.m31*mRight.m11 + + mLeft.m32*mRight.m21 + mLeft.m33*mRight.m31; + m32 = mLeft.m30*mRight.m02 + mLeft.m31*mRight.m12 + + mLeft.m32*mRight.m22 + mLeft.m33*mRight.m32; + m33 = mLeft.m30*mRight.m03 + mLeft.m31*mRight.m13 + + mLeft.m32*mRight.m23 + mLeft.m33*mRight.m33; + + this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; + this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; + this.m20 = m20; this.m21 = m21; this.m22 = m22; this.m23 = m23; + this.m30 = m30; this.m31 = m31; this.m32 = m32; this.m33 = m33; + } + + /** + * Transforms a 3D point vector using this transformation matrix. + * The result is written to the input point. + * + * @param point to transform + */ + public final void transformPoint(Vector point) { + double x = m00*point.getX() + m01*point.getY() + m02*point.getZ() + m03; + double y = m10*point.getX() + m11*point.getY() + m12*point.getZ() + m13; + double z = m20*point.getX() + m21*point.getY() + m22*point.getZ() + m23; + point.setX(x); + point.setY(y); + point.setZ(z); + } + + /** + * Transforms a 3D point vector using this transformation matrix. + * The result is written to the input point. + * + * @param point to transform + */ + public final void transformPoint(Vector3 point) { + double x = m00*point.x + m01*point.y + m02*point.z + m03; + double y = m10*point.x + m11*point.y + m12*point.z + m13; + double z = m20*point.x + m21*point.y + m22*point.z + m23; + point.x = x; + point.y = y; + point.z = z; + } + + /** + * Transforms a 4D point vector using this transformation matrix. + * The result is written to the input point. + * + * @param point to transform + */ + public final void transformPoint(Vector4 point) { + double x = m00 * point.x + m01 * point.y + m02 * point.z + m03 * point.w; + double y = m10 * point.x + m11 * point.y + m12 * point.z + m13 * point.w; + double z = m20 * point.x + m21 * point.y + m22 * point.z + m23 * point.w; + double w = m30 * point.x + m31 * point.y + m32 * point.z + m33 * point.w; + point.x = x; + point.y = y; + point.z = z; + point.w = w; + } + + /** + * Transforms all four points of a quad using this transformation matrix. + * + * @param quad to transform + */ + public final void transformQuad(Quad quad) { + transformPoint(quad.p0); + transformPoint(quad.p1); + transformPoint(quad.p2); + transformPoint(quad.p3); + } + + /** + * Obtains the absolute position vector of this matrix, equivalent to performing + * transformPoint with a zero vector. + * + * @return position vector + */ + public Vector3 toVector3() { + return new Vector3(m03, m13, m23); + } + + /** + * Obtains the absolute position vector of this matrix, equivalent to performing + * transformPoint with a zero vector. + * + * @return position vector + */ + public Vector toVector() { + return new Vector(m03, m13, m23); + } + + /** + * Obtains the absolute position vector and rotation yaw/pitch information of this matrix + * + * @param world The world to use for the Location + * @return location + */ + public Location toLocation(World world) { + Vector ypr = this.getYawPitchRoll(); + return new Location(world, m03, m13, m23, (float) ypr.getY(), (float) ypr.getX()); + } + + @SuppressWarnings("MethodDoesntCallSuperMethod") + @Override + public Matrix4x4 clone() { + return new Matrix4x4(this); + } + + @Override + public String toString() { + return "{" + + m00 + ", " + m01 + ", " + m02 + ", " + m03 + "\n " + + m10 + ", " + m11 + ", " + m12 + ", " + m13 + "\n " + + m20 + ", " + m21 + ", " + m22 + ", " + m23 + "\n " + + m30 + ", " + m31 + ", " + m32 + ", " + m33 + "}"; + } + + /** + * Creates a 4x4 matrix from 3 columns of a 3x3 matrix + * + * @param v0 column 0 + * @param v1 column 1 + * @param v2 column 2 + * @return 4x4 matrix + */ + public static Matrix4x4 fromColumns3x3(Vector v0, Vector v1, Vector v2) { + return new Matrix4x4( + v0.getX(), v1.getX(), v2.getX(), 0.0, + v0.getY(), v1.getY(), v2.getY(), 0.0, + v0.getZ(), v1.getZ(), v2.getZ(), 0.0, + 0.0, 0.0, 0.0, 1.0); + } + + /** + * Creates a 4x4 matrix by using the Location information of an Entity. + * This is equivalent to calling {@link #translateRotate(Location)} on an + * identity matrix. + * + * @param location + * @return transformation matrix for location + */ + public static Matrix4x4 fromLocation(Location location) { + Matrix4x4 result = new Matrix4x4(); + result.translateRotate(location); + return result; + } + + /** + * Creates a new 4x4 identity matrix. This has the initial values: + *
    +     * 1 0 0 0
    +     * 0 1 0 0
    +     * 0 0 1 0
    +     * 0 0 0 1
    +     * 
    + * + * @return identity matrix + */ + public static Matrix4x4 identity() { + return new Matrix4x4(); + } + + /** + * Computes the difference transformation between two matrices + * + * @param m1 Old transformation matrix + * @param m2 New transformation matrix + * @return Matrix that transforms the old matrix into the new matrix + */ + public static Matrix4x4 diff(Matrix4x4 m1, Matrix4x4 m2) { + Matrix4x4 diff = m1.clone(); + diff.invert(); + diff.multiply(m2); + return diff; + } + + /** + * Computes the difference rotation transformation between two matrices + * + * @param m1 Old transformation matrix + * @param m2 New transformation matrix + * @return Quaternion that rotates {@link #getRotation()} of the old matrix into the new matrix + */ + public static Quaternion diffRotation(Matrix4x4 m1, Matrix4x4 m2) { + return diff(m1, m2).getRotation(); + } + + /** + * Multiplies two matrices together, returning a new matrix with the result. + * + * @param mLeft Left matrix of the matrix multiplication + * @param mRight Right matrix of the matrix multiplication + * @return Result of the multiplication + */ + public static Matrix4x4 multiply(Matrix4x4 mLeft, Matrix4x4 mRight) { + Matrix4x4 result = new Matrix4x4(); + result.storeMultiply(mLeft, mRight); + return result; + } + + /** + * Multiplies two matrices together, storing the result in another matrix. + * The result matrix is allowed to be the same instance as one of the input matrices. + * + * @param mLeft Left matrix of the matrix multiplication + * @param mRight Right matrix of the matrix multiplication + * @param mResult Result of the multiplication is written to this matrix + */ + public static void multiply(Matrix4x4 mLeft, Matrix4x4 mRight, Matrix4x4 mResult) { + mResult.storeMultiply(mLeft, mRight); + } + + // From https://math.stackexchange.com/questions/296794 + public static Matrix4x4 computeProjectionMatrix(Vector3[] p) + { + Matrix4x4 m = new Matrix4x4( + p[0].x, p[1].x, p[2].x, 0.0f, + p[0].y, p[1].y, p[2].y, 1.0f, + p[0].z, p[1].z, p[2].z, 0.0f, + 1, 1, 1, 0); + + //TODO: For some reason we need to add a very small value to p[3].y to avoid glitching out + // Any reason why? Should this value be calculated from somewhere? View clipping plane? + // Or maybe the matrix inversion simply cannot handle an y value without it. + Vector4 p3 = new Vector4(p[3].x, p[3].y + 0.001f, p[3].z, 1.0f); + Matrix4x4 mInv = new Matrix4x4(m); + if (!mInv.invert()) { + return null; + } + mInv.transformPoint(p3); + + m.m00 *= p3.x; + m.m01 *= p3.y; + m.m02 *= p3.z; + m.m03 *= p3.w; + + m.m10 *= p3.x; + m.m11 *= p3.y; + m.m12 *= p3.z; + m.m13 *= p3.w; + + m.m20 *= p3.x; + m.m21 *= p3.y; + m.m22 *= p3.z; + m.m23 *= p3.w; + + m.m30 *= p3.x; + m.m31 *= p3.y; + m.m32 *= p3.z; + m.m33 *= p3.w; + + return m; + } +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/models/math/MatrixMath.java b/src/main/java/com/jverbruggen/jrides/models/math/MatrixMath.java new file mode 100644 index 00000000..4367202a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/math/MatrixMath.java @@ -0,0 +1,275 @@ +/** + * This code has been kindly borrowed from bergerkiller's BKCommonLib + * + * MIT License + * + * Copyright (C) 2013-2015 bergerkiller Copyright (C) 2016-2020 Berger Healer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, and/or sublicense the Software, + * and to permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.jverbruggen.jrides.models.math; + +public class MatrixMath { + /** + * Given a 4x4 array "matrix0", this function replaces it with the + * LU decomposition of a row-wise permutation of itself. The input + * parameters are "matrix0" and "dimen". The array "matrix0" is also + * an output parameter. The vector "row_perm[4]" is an output + * parameter that contains the row permutations resulting from partial + * pivoting. The output parameter "even_row_xchg" is 1 when the + * number of row exchanges is even, or -1 otherwise. Assumes data + * type is always double. + * + * This function is similar to luDecomposition, except that it + * is tuned specifically for 4x4 matrices. + * + * @return true if the matrix is nonsingular, or false otherwise. + */ + // + // Reference: Press, Flannery, Teukolsky, Vetterling, + // _Numerical_Recipes_in_C_, Cambridge University Press, + // 1988, pp 40-45. + // + public static boolean luDecomposition(double[] matrix0, + int[] row_perm) { + + double[] row_scale = new double[4]; + + // Determine implicit scaling information by looping over rows + { + int i, j; + int ptr, rs; + double big, temp; + + ptr = 0; + rs = 0; + + // For each row ... + i = 4; + while (i-- != 0) { + big = 0.0; + + // For each column, find the largest element in the row + j = 4; + while (j-- != 0) { + temp = matrix0[ptr++]; + temp = Math.abs(temp); + if (temp > big) { + big = temp; + } + } + + // Is the matrix singular? + if (big == 0.0) { + return false; + } + row_scale[rs++] = 1.0 / big; + } + } + + { + int j; + int mtx; + + mtx = 0; + + // For all columns, execute Crout's method + for (j = 0; j < 4; j++) { + int i, imax, k; + int target, p1, p2; + double sum, big, temp; + + // Determine elements of upper diagonal matrix U + for (i = 0; i < j; i++) { + target = mtx + (4*i) + j; + sum = matrix0[target]; + k = i; + p1 = mtx + (4*i); + p2 = mtx + j; + while (k-- != 0) { + sum -= matrix0[p1] * matrix0[p2]; + p1++; + p2 += 4; + } + matrix0[target] = sum; + } + + // Search for largest pivot element and calculate + // intermediate elements of lower diagonal matrix L. + big = 0.0; + imax = -1; + for (i = j; i < 4; i++) { + target = mtx + (4*i) + j; + sum = matrix0[target]; + k = j; + p1 = mtx + (4*i); + p2 = mtx + j; + while (k-- != 0) { + sum -= matrix0[p1] * matrix0[p2]; + p1++; + p2 += 4; + } + matrix0[target] = sum; + + // Is this the best pivot so far? + if ((temp = row_scale[i] * Math.abs(sum)) >= big) { + big = temp; + imax = i; + } + } + + if (imax < 0) { + return false; + } + + // Is a row exchange necessary? + if (j != imax) { + // Yes: exchange rows + k = 4; + p1 = mtx + (4*imax); + p2 = mtx + (4*j); + while (k-- != 0) { + temp = matrix0[p1]; + matrix0[p1++] = matrix0[p2]; + matrix0[p2++] = temp; + } + + // Record change in scale factor + row_scale[imax] = row_scale[j]; + } + + // Record row permutation + row_perm[j] = imax; + + // Is the matrix singular + // Was: + // matrix0[(mtx + (4*j) + j)] == 0.0 + // Changed it because of float range issues + final double SINGULAR_EP = 0.00001; + double v = matrix0[(mtx + (4*j) + j)]; + if (v >= -SINGULAR_EP && v <= SINGULAR_EP) { + return false; + } + + // Divide elements of lower diagonal matrix L by pivot + if (j != (4-1)) { + temp = 1.0 / (matrix0[(mtx + (4*j) + j)]); + target = mtx + (4*(j+1)) + j; + i = 3 - j; + while (i-- != 0) { + matrix0[target] *= temp; + target += 4; + } + } + } + } + + return true; + } + + /** + * Solves a set of linear equations. The input parameters "matrix1", + * and "row_perm" come from luDecompostionD4x4 and do not change + * here. The parameter "matrix2" is a set of column vectors assembled + * into a 4x4 matrix of floating-point values. The procedure takes each + * column of "matrix2" in turn and treats it as the right-hand side of the + * matrix equation Ax = LUx = b. The solution vector replaces the + * original column of the matrix. + * + * If "matrix2" is the identity matrix, the procedure replaces its contents + * with the inverse of the matrix from which "matrix1" was originally + * derived. + */ + // + // Reference: Press, Flannery, Teukolsky, Vetterling, + // _Numerical_Recipes_in_C_, Cambridge University Press, + // 1988, pp 44-45. + // + @SuppressWarnings("PointlessArithmeticExpression") + public static void luBacksubstitution(double[] matrix1, + int[] row_perm, + double[] matrix2) { + + int i, ii, ip, j, k; + int rp; + int cv, rv; + + // rp = row_perm; + rp = 0; + + // For each column vector of matrix2 ... + for (k = 0; k < 4; k++) { + // cv = &(matrix2[0][k]); + cv = k; + ii = -1; + + // Forward substitution + for (i = 0; i < 4; i++) { + double sum; + + ip = row_perm[rp+i]; + sum = matrix2[cv+4*ip]; + matrix2[cv+4*ip] = matrix2[cv+4*i]; + if (ii >= 0) { + // rv = &(matrix1[i][0]); + rv = i*4; + for (j = ii; j <= i-1; j++) { + sum -= matrix1[rv+j] * matrix2[cv+4*j]; + } + } + else if (sum != 0.0) { + ii = i; + } + matrix2[cv+4*i] = sum; + } + + // Backsubstitution + // rv = &(matrix1[3][0]); + rv = 3*4; + matrix2[cv+4*3] /= matrix1[rv+3]; + + rv -= 4; + matrix2[cv+4*2] = (matrix2[cv+4*2] - + matrix1[rv+3] * matrix2[cv+4*3]) / matrix1[rv+2]; + + rv -= 4; + matrix2[cv+4*1] = (matrix2[cv+4*1] - + matrix1[rv+2] * matrix2[cv+4*2] - + matrix1[rv+3] * matrix2[cv+4*3]) / matrix1[rv+1]; + + rv -= 4; + matrix2[cv+4*0] = (matrix2[cv+4*0] - + matrix1[rv+1] * matrix2[cv+4*1] - + matrix1[rv+2] * matrix2[cv+4*2] - + matrix1[rv+3] * matrix2[cv+4*3]) / matrix1[rv+0]; + } + } + + public static Matrix4x4 rotateTranslate(Vector3 originPosition, Quaternion originRotation, Vector3 offsetPosition, Quaternion offsetRotation){ + Matrix4x4 rotationMatrix = new Matrix4x4(); + rotationMatrix.translate(originPosition); + rotationMatrix.rotate(originRotation); + + rotationMatrix.rotate(offsetRotation); + rotationMatrix.translate(offsetPosition); + + return rotationMatrix; + } +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/models/math/Quad.java b/src/main/java/com/jverbruggen/jrides/models/math/Quad.java new file mode 100644 index 00000000..f48355d4 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/math/Quad.java @@ -0,0 +1,186 @@ +/** + * This code has been kindly borrowed from bergerkiller's BKCommonLib + * + * MIT License + * + * Copyright (C) 2013-2015 bergerkiller Copyright (C) 2016-2020 Berger Healer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, and/or sublicense the Software, + * and to permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.jverbruggen.jrides.models.math; + +import org.bukkit.block.BlockFace; + +public class Quad implements Comparable, Cloneable { + public Vector3 p0, p1, p2, p3; + public BlockFace face; + + public Quad() { + this.p0 = new Vector3(); + this.p1 = new Vector3(); + this.p2 = new Vector3(); + this.p3 = new Vector3(); + this.face = BlockFace.UP; + } + + protected Quad(Quad quad) { + this.p0 = quad.p0.clone(); + this.p1 = quad.p1.clone(); + this.p2 = quad.p2.clone(); + this.p3 = quad.p3.clone(); + this.face = quad.face; + } + + public Quad(BlockFace face, Vector3 from, Vector3 to) { + this(); + this.face = face; + if (face == BlockFace.UP) { + p1.x = from.x; + p1.z = to.z; + + p2.x = to.x; + p2.z = to.z; + + p3.x = to.x; + p3.z = from.z; + + p0.x = from.x; + p0.z = from.z; + + p0.y = p1.y = p2.y = p3.y = to.y; + } + if (face == BlockFace.DOWN) { + p1.x = from.x; + p1.z = from.z; + + p2.x = to.x; + p2.z = from.z; + + p3.x = to.x; + p3.z = to.z; + + p0.x = from.x; + p0.z = to.z; + + p0.y = p1.y = p2.y = p3.y = from.y; + } + if (face == BlockFace.SOUTH) { + p1.x = from.x; + p1.y = from.y; + + p2.x = to.x; + p2.y = from.y; + + p3.x = to.x; + p3.y = to.y; + + p0.x = from.x; + p0.y = to.y; + + p0.z = p1.z = p2.z = p3.z = to.z; + } + if (face == BlockFace.NORTH) { + p1.x = to.x; + p1.y = from.y; + + p2.x = from.x; + p2.y = from.y; + + p3.x = from.x; + p3.y = to.y; + + p0.x = to.x; + p0.y = to.y; + + p0.z = p1.z = p2.z = p3.z = from.z; + } + if (face == BlockFace.EAST) { + p1.y = from.y; + p1.z = to.z; + + p2.y = from.y; + p2.z = from.z; + + p3.y = to.y; + p3.z = from.z; + + p0.y = to.y; + p0.z = to.z; + + p0.x = p1.x = p2.x = p3.x = to.x; + } + if (face == BlockFace.WEST) { + p1.y = from.y; + p1.z = from.z; + + p2.y = from.y; + p2.z = to.z; + + p3.y = to.y; + p3.z = to.z; + + p0.y = to.y; + p0.z = from.z; + + p0.x = p1.x = p2.x = p3.x = from.x; + } + } + + /** + * Replaces points that equal points in this quad with the one of another quad. + * By merging the 6 quads of a cube can be manipulated with just 8 points. + * + * @param quad to merge points with + */ + public final void mergePoints(Quad quad) { + mergePoint(quad.p0); + mergePoint(quad.p1); + mergePoint(quad.p2); + mergePoint(quad.p3); + } + + private void mergePoint(Vector3 p) { + if (p0.equals(p)) p0 = p; + if (p1.equals(p)) p1 = p; + if (p2.equals(p)) p2 = p; + if (p3.equals(p)) p3 = p; + } + + public double depth() { + double d = p0.y; + if (p1.y < d) d = p1.y; + if (p2.y < d) d = p2.y; + if (p3.y < d) d = p3.y; + return d; + + //return (p0.y + p1.y + p2.y + p3.y) / 4.0f; + } + + @Override + public int compareTo(Quad o) { + return Double.compare(this.depth(), o.depth()); + } + + @SuppressWarnings("MethodDoesntCallSuperMethod") + @Override + public Quad clone() { + return new Quad(this); + } +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/models/math/Quaternion.java b/src/main/java/com/jverbruggen/jrides/models/math/Quaternion.java new file mode 100644 index 00000000..b16ae66b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/math/Quaternion.java @@ -0,0 +1,971 @@ +/** + * This code has been kindly borrowed from bergerkiller's BKCommonLib + * + * MIT License + * + * Copyright (C) 2013-2015 bergerkiller Copyright (C) 2016-2020 Berger Healer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, and/or sublicense the Software, + * and to permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.jverbruggen.jrides.models.math; + +import org.bukkit.util.Vector; + +import java.util.Iterator; +import java.util.List; + +/** + * A quaternion for performing rotations in 3D space. + * The quaternion is automatically normalized. + */ +public class Quaternion implements Cloneable { + private double x, y, z, w; + + public Quaternion() { + this.x = 0.0; + this.y = 0.0; + this.z = 0.0; + this.w = 1.0; + } + + public Quaternion(Quaternion quat) { + this.x = quat.x; + this.y = quat.y; + this.z = quat.z; + this.w = quat.w; + } + + public Quaternion(double x, double y, double z, double w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + this.normalize(); + } + + public double getX() { + return this.x; + } + + public double getY() { + return this.y; + } + + public double getZ() { + return this.z; + } + + public double getW() { + return this.w; + } + + /** + * Sets this Quaternion to the identity quaternion (0,0,0,1) + */ + public void setIdentity() { + this.x = 0.0; + this.y = 0.0; + this.z = 0.0; + this.w = 1.0; + } + + /** + * Sets this Quaternion to the values of another Quaternion + * + * @param q to set to + */ + public void setTo(Quaternion q) { + this.x = q.x; + this.y = q.y; + this.z = q.z; + this.w = q.w; + } + + /** + * Calculates the dot product of this Quaternion with another + * + * @param q other quaternion + * @return dot product + */ + public double dot(Quaternion q) { + return this.x * q.x + this.y * q.y + this.z * q.z + this.w * q.w; + } + + /** + * Transforms a point, applying the rotation of this quaternion with 0,0,0 as origin. + * + * @param point to rotate using this quaternion + */ + public void transformPoint(Vector point) { + double px = point.getX(); + double py = point.getY(); + double pz = point.getZ(); + point.setX( px + 2.0 * (px*(-y*y-z*z) + py*(x*y-z*w) + pz*(x*z+y*w)) ); + point.setY( py + 2.0 * (px*(x*y+z*w) + py*(-x*x-z*z) + pz*(y*z-x*w)) ); + point.setZ( pz + 2.0 * (px*(x*z-y*w) + py*(y*z+x*w) + pz*(-x*x-y*y)) ); + } + + /** + * Transforms a point, applying the rotation of this quaternion with 0,0,0 as origin. + * + * @param point to rotate using this quaternion + */ + public void transformPoint(Vector3 point) { + double px = point.getX(); + double py = point.getY(); + double pz = point.getZ(); + point.x = ( px + 2.0 * (px*(-y*y-z*z) + py*(x*y-z*w) + pz*(x*z+y*w)) ); + point.y = ( py + 2.0 * (px*(x*y+z*w) + py*(-x*x-z*z) + pz*(y*z-x*w)) ); + point.z = ( pz + 2.0 * (px*(x*z-y*w) + py*(y*z+x*w) + pz*(-x*x-y*y)) ); + } + + /** + * Retrieves the right vector, which is the result of transforming a (1,0,0) point + * with this Quaternion. + * + * @return right vector + */ + public Vector rightVector() { + return new Vector(1.0 + 2.0 * (-y*y-z*z), 2.0 * (x*y+z*w), 2.0 * (x*z-y*w)); + } + + /** + * Retrieves the up vector, which is the result of transforming a (0,1,0) point + * with this Quaternion. + * + * @return up vector + */ + public Vector upVector() { + return new Vector(2.0 * (x*y-z*w), 1.0 + 2.0 * (-x*x-z*z), 2.0 * (y*z+x*w)); + } + + /** + * Retrieves the forward vector, which is the result of transforming a (0,0,1) point + * with this Quaternion. + * + * @return forward vector + */ + public Vector forwardVector() { + return new Vector(2.0 * (x*z+y*w), 2.0 * (y*z-x*w), 1.0 + 2.0 * (-x*x-y*y)); + } + + /** + * Divides this quaternion by another quaternion. This operation is equivalent to multiplying + * with the quaternion after calling {@link #invert()} on it. + * + * @param quat to divide with + */ + public void divide(Quaternion quat) { + double x = this.w * -quat.x + this.x * quat.w + this.y * -quat.z - this.z * -quat.y; + double y = this.w * -quat.y + this.y * quat.w + this.z * -quat.x - this.x * -quat.z; + double z = this.w * -quat.z + this.z * quat.w + this.x * -quat.y - this.y * -quat.x; + double w = this.w * quat.w - this.x * -quat.x - this.y * -quat.y - this.z * -quat.z; + this.x = x; this.y = y; this.z = z; this.w = w; + this.normalize(); + } + + /** + * Multiplies this quaternion with another quaternion. The result is stored in this quaternion. + * + * @param quat to multiply with + */ + public void multiply(Quaternion quat) { + double x = this.w * quat.x + this.x * quat.w + this.y * quat.z - this.z * quat.y; + double y = this.w * quat.y + this.y * quat.w + this.z * quat.x - this.x * quat.z; + double z = this.w * quat.z + this.z * quat.w + this.x * quat.y - this.y * quat.x; + double w = this.w * quat.w - this.x * quat.x - this.y * quat.y - this.z * quat.z; + this.x = x; this.y = y; this.z = z; this.w = w; + this.normalize(); + } + + /** + * Multiplies this Quaternion with a rotation around an axis + * + * @param axis vector + * @param angleDegrees to rotate in degrees + */ + public final void rotateAxis(Vector axis, double angleDegrees) { + rotateAxis(axis.getX(), axis.getY(), axis.getZ(), angleDegrees); + } + + /** + * Multiplies this Quaternion with a rotation around an axis + * + * @param axisX vector coordinate + * @param axisY vector coordinate + * @param axisZ vector coordinate + * @param angleDegrees to rotate in degrees + */ + public final void rotateAxis(double axisX, double axisY, double axisZ, double angleDegrees) { + this.multiply(Quaternion.fromAxisAngles(axisX, axisY, axisZ, angleDegrees)); + } + + /** + * Multiplies this quaternion with a rotation transformation in yaw/pitch/roll, based on the Minecraft + * coordinate system. This will differ slightly from the standard rotateX/Y/Z functions. + * + * @param rotation (x=pitch, y=yaw, z=roll) + */ + public final void rotateYawPitchRoll(Vector3 rotation) { + rotateYawPitchRoll(rotation.x, rotation.y, rotation.z); + } + + /** + * Multiplies this quaternion with a rotation transformation in yaw/pitch/roll, based on the Minecraft + * coordinate system. This will differ slightly from the standard rotateX/Y/Z functions. + * + * @param rotation (x=pitch, y=yaw, z=roll) + */ + public final void rotateYawPitchRoll(Vector rotation) { + rotateYawPitchRoll(rotation.getX(), rotation.getY(), rotation.getZ()); + } + + /** + * Multiplies this quaternion with a rotation transformation in yaw/pitch/roll, based on the Minecraft + * coordinate system. This will differ slightly from the standard rotateX/Y/Z functions. + * + * @param pitch rotation (X) + * @param yaw rotation (Y) + * @param roll rotation (Z) + */ + public final void rotateYawPitchRoll(double pitch, double yaw, double roll) { + this.rotateY(-yaw); + this.rotateX(pitch); + this.rotateZ(roll); + } + + public final void rotateYawPitchRollRadians(double pitch, double yaw, double roll) { + this.rotateYRadians(-yaw); + this.rotateXRadians(pitch); + this.rotateZRadians(roll); + } + + /** + * Deduces the yaw/pitch/roll values in degrees that this quaternion transforms objects with + * + * @return axis rotations: {x=pitch, y=yaw, z=roll} + */ + public final Vector getYawPitchRoll() { + return getYawPitchRoll(x, y, z, w); + } + + /** + * Deduces the pitch component (x) of {@link #getYawPitchRoll()} + * + * @return pitch + */ + public final double getPitch() { + return getPitch(x, y, z, w); + } + + /** + * Deduces the yaw component (y) of {@link #getYawPitchRoll()} + * !! Uses range [-180, 180], wrap [0, 360] degrees using MathUtil.wrapAngle + * + * @return yaw + */ + public final double getYaw() { + return getYaw(x, y, z, w); + } + + public final double getPacketYaw(){ + return (getYaw() - 90) * 256/360; + } + + /** + * Deduces the roll component (z) of {@link #getYawPitchRoll()} + * + * @return roll + */ + public final double getRoll() { + return getRoll(x, y, z, w); + } + + // Helper function reused by Matrix4x4, portion cut out from getYawPitchRoll() + protected static double getYaw(double x, double y, double z, double w) { + final double test = 2.0 * (w * x - y * z); + if (Math.abs(test) < (1.0 - 1E-15)) { + double yaw = CommonTrigMath.atan2(-2.0 * (w * y + z * x), 1.0 - 2.0 * (x * x + y * y)); + double roll_x = 0.5 - (x * x + z * z); + if (roll_x <= 0.0 && (Math.abs((w * z + x * y)) > roll_x)) { + yaw += (yaw < 0.0) ? Math.PI : -Math.PI; + } + return Math.toDegrees(yaw); + } else if (test < 0.0) { + return Math.toDegrees(-2.0 * CommonTrigMath.atan2(z, w)); + } else { + return Math.toDegrees(2.0 * CommonTrigMath.atan2(z, w)); + } + } + + // Helper function reused by Matrix4x4, portion cut out from getYawPitchRoll() + protected static double getPitch(double x, double y, double z, double w) { + final double test = 2.0 * (w * x - y * z); + if (Math.abs(test) < (1.0 - 1E-15)) { + double pitch = Math.asin(test); + double roll_x = 0.5 - (x * x + z * z); + if (roll_x <= 0.0 && (Math.abs((w * z + x * y)) > roll_x)) { + pitch = -pitch; + pitch += (pitch < 0.0) ? Math.PI : -Math.PI; + } + return Math.toDegrees(pitch); + } else if (test < 0.0) { + return -90.0; + } else { + return 90.0; + } + } + + // Helper function reused by Matrix4x4, portion cut out from getYawPitchRoll() + protected static double getRoll(double x, double y, double z, double w) { + final double test = 2.0 * (w * x - y * z); + if (Math.abs(test) < (1.0 - 1E-15)) { + double roll = CommonTrigMath.atan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (x * x + z * z)); + if (Math.abs(roll) > (0.5 * Math.PI)) { + roll += (roll < 0.0) ? Math.PI : -Math.PI; + } + return Math.toDegrees(roll); + } else { + return 0.0; + } + } + + // Helper function reused by Matrix4x4 + protected static Vector getYawPitchRoll(double x, double y, double z, double w) { + final double test = 2.0 * (w * x - y * z); + if (Math.abs(test) < (1.0 - 1E-15)) { + // Standard angle + double roll = CommonTrigMath.atan2(2.0 * (w * z + x * y), 1.0 - 2.0 * (x * x + z * z)); + double pitch = Math.asin(test); + double yaw = CommonTrigMath.atan2(-2.0 * (w * y + z * x), 1.0 - 2.0 * (x * x + y * y)); + + // This means the following: + // roll = Math.atan2(rightVector.getY(), upVector.getY()); + // pitch = Math.asin(-forwardVector.getY()); + // yaw = Math.atan2(forwardVector.getX(), forwardVector.getZ()); + + // Reduce roll if it is > 90.0 degrees + // This can be done thanks to the otherwise annoying 'gymbal lock' effect + // We can rotate yaw and roll with 180 degrees, and invert pitch to adjust + // This results in the equivalent rotation + if (Math.abs(roll) > (0.5 * Math.PI)) { + roll += (roll < 0.0) ? Math.PI : -Math.PI; + yaw += (yaw < 0.0) ? Math.PI : -Math.PI; + pitch = -pitch; + pitch += (pitch < 0.0) ? Math.PI : -Math.PI; + } + + return new Vector(Math.toDegrees(pitch), Math.toDegrees(yaw), Math.toDegrees(roll)); + + } else if (test < 0.0) { + // This is at the pitch=-90.0 singularity + // All we can do is yaw (or roll) around the vertical axis + return new Vector(-90.0, Math.toDegrees(-2.0 * CommonTrigMath.atan2(z, w)), 0.0); + + } else { + // This is at the pitch=90.0 singularity + // All we can do is yaw (or roll) around the vertical axis + return new Vector(90.0, Math.toDegrees(2.0 * CommonTrigMath.atan2(z, w)), 0.0); + } + } + + /** + * Rotates the Quaternion 180 degrees around the x-axis + */ + public final void rotateXFlip() { + rotateX_unsafe(0.0, 1.0); + } + + /** + * Rotates the Quaternion an angle around the x-axis + * + * @param angleDegrees to rotate + */ + public final void rotateX(double angleDegrees) { + if (angleDegrees != 0.0) { + double r = 0.5 * Math.toRadians(angleDegrees); + rotateX_unsafe(Math.cos(r), Math.sin(r)); + } + } + + public final void rotateXRadians(double angleRadians) { + if (angleRadians != 0.0) { + double r = 0.5 * angleRadians; + rotateX_unsafe(Math.cos(r), Math.sin(r)); + } + } + + /** + * Rotates the Quaternion an angle around the X-axis, the angle defined by the y/z vector. + * + * @param y + * @param z + */ + public final void rotateX(double y, double z) { + double r = halfcosatan2(z, y); + rotateX_unsafe(Math.sqrt(0.5 + r), Math.sqrt(0.5 - r)); + } + + private void rotateX_unsafe(double fy, double fz) { + double x = this.x * fy + this.w * fz; + double y = this.y * fy + this.z * fz; + double z = this.z * fy - this.y * fz; + double w = this.w * fy - this.x * fz; + this.x = x; this.y = y; this.z = z; this.w = w; + this.normalize(); + } + + /** + * Rotates the Quaternion 180 degrees around the y-axis + */ + public final void rotateYFlip() { + rotateY_unsafe(0.0, 1.0); + } + + /** + * Rotates the Quaternion an angle around the y-axis + * Note: If rotating for yaw, Y should be negative + * + * @param angleDegrees to rotate + */ + public final void rotateY(double angleDegrees) { + if (angleDegrees != 0.0) { + double r = 0.5 * Math.toRadians(angleDegrees); + rotateY_unsafe(Math.cos(r), Math.sin(r)); + } + } + + public final void rotateYRadians(double angleRadians) { + if (angleRadians != 0.0) { + double r = 0.5 * angleRadians; + rotateY_unsafe(Math.cos(r), Math.sin(r)); + } + } + + /** + * Rotates the Quaternion an angle around the y-axis, the angle defined by the x/z vector. + * + * @param x + * @param z + */ + public final void rotateY(double x, double z) { + double r = halfcosatan2(z, x); + rotateY_unsafe(Math.sqrt(0.5 + r), Math.sqrt(0.5 - r)); + } + + private void rotateY_unsafe(double fx, double fz) { + double x = this.x * fx - this.z * fz; + double y = this.y * fx + this.w * fz; + double z = this.z * fx + this.x * fz; + double w = this.w * fx - this.y * fz; + this.x = x; this.y = y; this.z = z; this.w = w; + this.normalize(); + } + + /** + * Rotates the Quaternion 180 degrees around the z-axis + */ + public final void rotateZFlip() { + rotateZ_unsafe(0.0, 1.0); + } + + /** + * Rotates the Quaternion an angle around the z-axis + * + * @param angleDegrees to rotate + */ + public final void rotateZ(double angleDegrees) { + if (angleDegrees != 0.0) { + double r = 0.5 * Math.toRadians(angleDegrees); + rotateZ_unsafe(Math.cos(r), Math.sin(r)); + } + } + + public final void rotateZRadians(double angleRadians) { + if (angleRadians != 0.0) { + double r = 0.5 * angleRadians; + rotateZ_unsafe(Math.cos(r), Math.sin(r)); + } + } + + /** + * Rotates the Quaternion an angle around the z-axis, the angle defined by the x/y vector. + * + * @param x + * @param y + */ + public final void rotateZ(double x, double y) { + double r = halfcosatan2(y, x); + rotateZ_unsafe(Math.sqrt(0.5 + r), Math.sqrt(0.5 - r)); + } + + private void rotateZ_unsafe(double fx, double fy) { + double x = this.x * fx + this.y * fy; + double y = this.y * fx - this.x * fy; + double z = this.z * fx + this.w * fy; + double w = this.w * fx - this.z * fy; + this.x = x; this.y = y; this.z = z; this.w = w; + this.normalize(); + } + + /** + * Converts the rotation transformations defined in this quaternion to a + * 4x4 transformation matrix. This is as if the unit matrix was multiplied + * with this quaternion. + * + * @return 4x4 transformation matrix. + */ + public Matrix4x4 toMatrix4x4() { + return new Matrix4x4( + 1.0 - 2.0*y*y - 2.0*z*z, 2.0*x*y - 2.0*z*w, 2.0*x*z + 2.0*y*w, 0.0, + 2.0*x*y + 2.0*z*w, 1.0 - 2.0*x*x - 2.0*z*z, 2.0*y*z - 2.0*x*w, 0.0, + 2.0*x*z - 2.0*y*w, 2.0*y*z + 2.0*x*w, 1.0 - 2.0*x*x - 2.0*y*y, 0.0, + 0.0, 0.0, 0.0, 1.0 + ); + } + + /** + * Inverts this Quaternion. + */ + public void invert() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + } + + private void normalize() { + double f = MathUtil.getNormalizationFactor(this.x, this.y, this.z, this.w); + this.x *= f; this.y *= f; this.z *= f; this.w *= f; + } + + @SuppressWarnings("MethodDoesntCallSuperMethod") + @Override + public Quaternion clone() { + return new Quaternion(this); + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } else if (o instanceof Quaternion) { + Quaternion q = (Quaternion) o; + return q.x == this.x && q.y == this.y && q.z == this.z && q.w == this.w; + } else { + return false; + } + } + + @Override + public String toString() { + return "{" + this.x + ", " + this.y + ", " + this.z + ", " + this.w + "}"; + } + + public String toShortString(){ + return "{" + ((double)(int)(this.x*10))/10 + ", " + ((double)(int)(this.y*10))/10 + ", " + ((double)(int)(this.z*10))/10 + ", " + ((double)(int)(this.w*10))/10 + "}"; + } + + /** + * Creates a new identity quaternion + * + * @return identity quaternion (x=0, y=0, z=0, w=1) + */ + public static Quaternion identity() { + return new Quaternion(); + } + + /** + * Performs a multiplication between two quaternions. + * A new quaternion instance is returned. + * + * @param q1 + * @param q2 + * @return q1 x q2 + */ + public static Quaternion multiply(Quaternion q1, Quaternion q2) { + Quaternion result = q1.clone(); + result.multiply(q2); + return result; + } + + /** + * Performs a division between two quaternions. + * A new quaternion instance is returned. + * + * @param q1 + * @param q2 + * @return q1 / q2 + */ + public static Quaternion divide(Quaternion q1, Quaternion q2) { + Quaternion result = q1.clone(); + result.divide(q2); + return result; + } + + /** + * Computes the difference transformation between two quaternions + * + * @param q1 Old rotation transformation quaternion + * @param q2 New rotation transformation quaternion + * @return Quaternion that rotates the old quaternion into the new quaternion + */ + public static Quaternion diff(Quaternion q1, Quaternion q2) { + Quaternion diff = q1.clone(); + diff.invert(); + diff.multiply(q2); + return diff; + } + + /** + * Creates a quaternion for a rotation around an axis + * + * @param axis + * @param angleDegrees + * @return quaternion for the rotation around the axis + */ + public static Quaternion fromAxisAngles(Vector3 axis, double angleDegrees) { + return fromAxisAngles(axis.x, axis.y, axis.z, angleDegrees); + } + + /** + * Creates a quaternion for a rotation around an axis + * + * @param axis + * @param angleDegrees + * @return quaternion for the rotation around the axis + */ + public static Quaternion fromAxisAngles(Vector axis, double angleDegrees) { + return fromAxisAngles(axis.getX(), axis.getY(), axis.getZ(), angleDegrees); + } + + /** + * Creates a quaternion for a rotation around an axis + * + * @param axisX + * @param axisY + * @param axisZ + * @param angleDegrees + * @return quaternion for the rotation around the axis + */ + public static Quaternion fromAxisAngles(double axisX, double axisY, double axisZ, double angleDegrees) { + double r = 0.5 * Math.toRadians(angleDegrees); + double f = Math.sin(r); + return new Quaternion(f*axisX, f*axisY, f*axisZ, Math.cos(r)); + } + + /** + * Creates a quaternion from yaw/pitch/roll rotations as performed by Minecraft + * + * @param rotation (x=pitch, y=yaw, z=roll) + * @return quaternion for the yaw/pitch/roll rotation + */ + public static Quaternion fromYawPitchRoll(Vector rotation) { + return fromYawPitchRoll(rotation.getX(), rotation.getY(), rotation.getZ()); + } + + public static Quaternion fromDoubleList(List doubleList) { + if (doubleList.size() != 3) throw new RuntimeException("Size of double list has to be 3"); + return fromYawPitchRoll(doubleList.get(0), doubleList.get(1), doubleList.get(2)); + } + + /** + * Creates a quaternion from yaw/pitch/roll rotations as performed by Minecraft + * + * @param pitch rotation (X) + * @param yaw rotation (Y) + * @param roll rotation (Z) + * @return quaternion for the yaw/pitch/roll rotation + */ + public static Quaternion fromYawPitchRoll(double pitch, double yaw, double roll) { + //TODO: Can be optimized to reduce the number of multiplications + Quaternion quat = new Quaternion(); + quat.rotateYawPitchRoll(pitch, yaw, roll); + return quat; + } + + /** + * Creates a quaternion that transforms the input vector (u) into the output vector (v). + * The vectors do not have to be unit vectors for this function to work. + * The d vector specifies an axis to rotate around when a 180-degree rotation is encountered. + * + * @param u input vector (from) + * @param v expected output vector (to) + * @param d direction axis around which to rotate for 180-degree angles + * @return quaternion that rotates u to become v + */ + public static Quaternion fromToRotation(Vector u, Vector v, Vector d) { + // xyz = cross(u, v), w = dot(u, v) + // add magnitude of quaternion to w, then normalize it + double dot = u.dot(v); + Quaternion q = new Quaternion(); + q.x = u.getY() * v.getZ() - v.getY() * u.getZ(); + q.y = u.getZ() * v.getX() - v.getZ() * u.getX(); + q.z = u.getX() * v.getY() - v.getX() * u.getY(); + q.w = dot; + q.w += Math.sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w); + q.normalize(); + + // there is a special case for opposite vectors + // here the quaternion ends up being 0,0,0,0 + // after normalization the terms are NaN as a result (0xinf=NaN) + if (Double.isNaN(q.w)) { + q.x = d.getX(); + q.y = d.getY(); + q.z = d.getZ(); + q.w = 0.0; + q.normalize(); + } + return q; + } + + /** + * Creates a quaternion that transforms the input vector (u) into the output vector (v). + * The vectors do not have to be unit vectors for this function to work. + * + * @param u input vector (from) + * @param v expected output vector (to) + * @return quaternion that rotates u to become v + */ + public static Quaternion fromToRotation(Vector u, Vector v) { + // xyz = cross(u, v), w = dot(u, v) + // add magnitude of quaternion to w, then normalize it + double dot = u.dot(v); + Quaternion q = new Quaternion(); + q.x = u.getY() * v.getZ() - v.getY() * u.getZ(); + q.y = u.getZ() * v.getX() - v.getZ() * u.getX(); + q.z = u.getX() * v.getY() - v.getX() * u.getY(); + q.w = dot; + q.w += Math.sqrt(q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w); + q.normalize(); + + // there is a special case for opposite vectors + // here the quaternion ends up being 0,0,0,0 + // after normalization the terms are NaN as a result (0xinf=NaN) + if (Double.isNaN(q.w)) { + if (dot > 0.0) { + // Identity Quaternion + q.setIdentity(); + } else { + // Rotation of 180 degrees around a certain axis + // First try axis X, then try axis Y + // The cross product with either vector is used for the axis + double norm = MathUtil.getNormalizationFactor(u.getZ(), u.getY()); + if (Double.isInfinite(norm)) { + norm = MathUtil.getNormalizationFactor(u.getZ(), u.getX()); + q.x = norm * u.getZ(); + q.y = 0.0; + q.z = norm * -u.getX(); + q.w = 0.0; + } else { + q.x = 0.0; + q.y = norm * -u.getZ(); + q.z = norm * u.getY(); + q.w = 0.0; + } + } + } + return q; + } + + /** + * Creates a quaternion that transforms a forward vector (0, 0, 1) into the output vector (v). + * The vector does not have to be a unit vector for this function to work. + * + * @param dir expected output vector (to) + * @return quaternion that rotates (0,0,1) to become v + */ + public static Quaternion fromLookDirection(Vector dir) { + Quaternion q = new Quaternion(-dir.getY(), dir.getX(), 0.0, dir.getZ() + dir.length()); + + // there is a special case when dir is (0, 0, -1) + if (Double.isNaN(q.w)) { + q.x = 0.0; + q.y = 1.0; + q.z = 0.0; + q.w = 0.0; + } + return q; + } + + /** + * Creates a quaternion that 'looks' into a given direction, with a known 'up' vector + * to dictate roll around that direction axis. + * + * @param dir to look into + * @param up direction + * @return Quaternion with the look-direction transformation + */ + public static Quaternion fromLookDirection(Vector dir, Vector up) { + // Use the 3x3 rotation matrix solution found on SO, combined with a getRotation() + // https://stackoverflow.com/a/18574797 + + Vector D = dir.clone().normalize(); + Vector S = up.clone().crossProduct(dir).normalize(); + Vector U = D.clone().crossProduct(S); + Quaternion result = Matrix4x4.fromColumns3x3(S, U, D).getRotation(); + + // Fix NaN as a result of dir == up + if (Double.isNaN(result.x)) { + return fromLookDirection(dir); + } else { + return result; + } + } + + public static Quaternion fromAnglesVector(Vector3 anglesVector){ + Quaternion quaternion = new Quaternion(); + + if(anglesVector != null) + quaternion.rotateYawPitchRoll(anglesVector.getX(), anglesVector.getY(), anglesVector.getZ()); + + return quaternion; + } + + /** + * Performs a linear interpolation between two quaternions. + * Separate theta values can be specified to set how much of each quaternion to keep + * + * @param q0 quaternion at theta=0 + * @param q1 quaternion at theta=1 + * @param t0 theta value for q0 amount (range 0 to 1) + * @param t1 theta value for q1 amount (range 0 to 1) + * @return lerp result + */ + public static Quaternion lerp(Quaternion q0, Quaternion q1, double t0, double t1) { + return new Quaternion(t0 * q0.x + t1 * q1.x, + t0 * q0.y + t1 * q1.y, + t0 * q0.z + t1 * q1.z, + t0 * q0.w + t1 * q1.w); + } + + /** + * Performs a linear interpolation between two quaternions. + * + * @param q0 quaternion at theta=0 + * @param q1 quaternion at theta=1 + * @param theta value (range 0 to 1) + * @return lerp result + */ + public static Quaternion lerp(Quaternion q0, Quaternion q1, double theta) { + return lerp(q0, q1, 1.0 - theta, theta); + } + + /** + * Performs a spherical interpolation between two quaternions. + * + * @param q0 quaternion at theta=0 + * @param q1 quaternion at theta=0 + * @param theta value (range 0 to 1) + * @return slerp result + */ + public static Quaternion slerp(Quaternion q0, Quaternion q1, double theta) { + Quaternion qs = q1.clone(); + double dot = q0.dot(q1); + + // Invert quaternion when dot < 0 to simplify maths + if (dot < 0.0) { + dot = -dot; + qs.x = -qs.x; + qs.y = -qs.y; + qs.z = -qs.z; + qs.w = -qs.w; + } + + // Above this a lerp is adequate + if (dot >= 0.95) { + return lerp(q0, qs, theta); + } + + // Linear interpolation using sines + double angle = Math.acos(dot); + double qd = 1.0 / Math.sin(angle); + double q0f = qd * Math.sin(angle*(1.0-theta)); + double qsf = qd * Math.sin(angle*theta); + return lerp(q0, qs, q0f, qsf); + } + + /** + * Produces an average rotation from several different rotation values. + * If only one rotation value is specified, then that one value is returned. + * If no rotation values are specified, identity is returned. + * The returned Quaternion is always a copy. + * + * @param values Iterable of Quaternion rotation values + * @return average rotation Quaternion + */ + public static Quaternion average(Iterable values) { + Iterator iter = values.iterator(); + + // No values, return identity + if (!iter.hasNext()) { + return identity(); + } + + // Only one value, return the one value (make sure to clone!) + Quaternion first = iter.next(); + if (!iter.hasNext()) { + return first.clone(); + } + + // Build up an average + int num_values = 1; + Quaternion result = first.clone(); + do { + Quaternion next = iter.next(); + if (first.dot(next) >= 0.0) { + result.x += next.x; + result.y += next.y; + result.z += next.z; + result.w += next.w; + } else { + result.x -= next.x; + result.y -= next.y; + result.z -= next.z; + result.w -= next.w; + } + num_values++; + } while (iter.hasNext()); + + // Divide by the number of values, then normalize the result + double fact = 1.0 / (double) num_values; + result.x *= fact; + result.y *= fact; + result.z *= fact; + result.w *= fact; + result.normalize(); + return result; + } + + // This method is used often for the two-arg rotateX/Y/Z functions + // Optimized equivalent of 0.5 * Math.cos(Math.atan2(y, x)) + private static double halfcosatan2(double y, double x) { + double tmp = y / x; + tmp *= tmp; + tmp += 1.0; + return ((x < 0.0) ? -0.5 : 0.5) / Math.sqrt(tmp); + } + + public void copyFrom(Quaternion orientation) { + this.x = orientation.getX(); + this.y = orientation.getY(); + this.z = orientation.getZ(); + this.w = orientation.getW(); + } +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/models/math/SpeedUtil.java b/src/main/java/com/jverbruggen/jrides/models/math/SpeedUtil.java new file mode 100644 index 00000000..eb139f73 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/math/SpeedUtil.java @@ -0,0 +1,41 @@ +package com.jverbruggen.jrides.models.math; + +public class SpeedUtil { + public static double positionStartBraking(double currentSpeed, double acceleration, double targetPosition, double targetSpeed){ + double dSpeed = targetSpeed - currentSpeed; + + double timeUntilStandStill = dSpeed / acceleration; + double decelerationDistance = (dSpeed * timeUntilStandStill) - (.5f * acceleration * (timeUntilStandStill*timeUntilStandStill)); + + return targetPosition + decelerationDistance; + } + + public static boolean hasPassed(double from, double currentPosition, double to, boolean positiveFrom) { + return hasPassed(from, currentPosition, to, positiveFrom, 0d); + } + + public static boolean hasPassed(double from, double currentPosition, double to, boolean positiveFrom, double margin) { + if(positiveFrom){ + return !inRange(from, currentPosition, to) || currentPosition == to; + }else{ + return !inRange(-from, -currentPosition, -to) || currentPosition == to; + } + } + + public static boolean aboveInRange(double from, double currentPosition, double target, double to, boolean positiveFrom){ + if(positiveFrom) + return inRange(from, currentPosition, target); + else + return inRange(-from, -currentPosition, -target); + } + + public static boolean inRange(double rangeLower, double x, double rangeUpper){ + boolean normalBetweenState = rangeLower <= rangeUpper; + boolean rotateBetweenState = rangeLower > rangeUpper; + + boolean inNormalState = normalBetweenState && (rangeLower <= x && x <= rangeUpper); + boolean inRotateState = rotateBetweenState && (rangeLower <= x || x <= rangeUpper); + + return inNormalState || inRotateState; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/math/Task.java b/src/main/java/com/jverbruggen/jrides/models/math/Task.java new file mode 100644 index 00000000..87e77b08 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/math/Task.java @@ -0,0 +1,128 @@ +/** + * This code has been kindly borrowed from bergerkiller's BKCommonLib + * + * MIT License + * + * Copyright (C) 2013-2015 bergerkiller Copyright (C) 2016-2020 Berger Healer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, and/or sublicense the Software, + * and to permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.jverbruggen.jrides.models.math; + +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; + +public abstract class Task implements Runnable { + + private final JavaPlugin plugin; + private int id = -1; + + public Task(final JavaPlugin plugin) { + this.plugin = plugin; + } + + /** + * Gets the Plugin this Task belongs to + * + * @return Plugin + */ + public final JavaPlugin getPlugin() { + return this.plugin; + } + + /** + * Checks if this Task is currently being executed + * + * @return True if running, False if not + */ + public boolean isRunning() { + return this.id != -1 && Bukkit.getServer().getScheduler().isCurrentlyRunning(this.id); + } + + /** + * Checks whether this Task is still queued + * + * @return True if still queued, False if not + */ + public boolean isQueued() { + return Bukkit.getServer().getScheduler().isQueued(this.id); + } + + /** + * Stops a Task + * + * @param task to stop, ignored if null + * @return True if stopped, False if not + */ + public static boolean stop(Task task) { + if (task == null) { + return false; + } + task.stop(); + return true; + } + + /** + * Stops this Task from executing + * + * @return This Task + */ + public Task stop() { + if (this.id != -1) { + Bukkit.getServer().getScheduler().cancelTask(this.id); + this.id = -1; + } + return this; + } + + /** + * Starts this Task the very next tick + * + * @return This Task + */ + public Task start() { + this.id = this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, this); + return this; + } + + /** + * Starts this Task after the delay specified + * + * @param delay in ticks + * @return This Task + */ + public Task start(long delay) { + this.id = this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, this, delay); + return this; + } + + /** + * Starts this Task after the delay specified, and keeps running it at the + * interval + * + * @param delay in ticks + * @param interval in ticks + * @return This Task + */ + public Task start(long delay, long interval) { + this.id = this.plugin.getServer().getScheduler().scheduleSyncRepeatingTask(this.plugin, this, delay, interval); + return this; + } +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/models/math/Vector2.java b/src/main/java/com/jverbruggen/jrides/models/math/Vector2.java new file mode 100644 index 00000000..dc9da646 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/math/Vector2.java @@ -0,0 +1,53 @@ +/** + * This code has been kindly borrowed from bergerkiller's BKCommonLib + * + * MIT License + * + * Copyright (C) 2013-2015 bergerkiller Copyright (C) 2016-2020 Berger Healer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, and/or sublicense the Software, + * and to permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.jverbruggen.jrides.models.math; + +public class Vector2 { + public double x; + public double y; + + public Vector2() { + this.x = 0.0; + this.y = 0.0; + } + + public Vector2(double x, double y) { + this.x = x; + this.y = y; + } + + public double distance(Vector2 p) { + double dx = (p.x - this.x); + double dy = (p.y - this.y); + return Math.sqrt(dx*dx+dy*dy); + } + + @Override + public String toString() { + return "{x=" + x + ", y=" + y + "}"; + } +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/models/math/Vector3.java b/src/main/java/com/jverbruggen/jrides/models/math/Vector3.java new file mode 100644 index 00000000..5a40942b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/math/Vector3.java @@ -0,0 +1,323 @@ +/** + * This code has been kindly borrowed from bergerkiller's BKCommonLib + * + * MIT License + * + * Copyright (C) 2013-2015 bergerkiller Copyright (C) 2016-2020 Berger Healer + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, and/or sublicense the Software, + * and to permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package com.jverbruggen.jrides.models.math; + +import com.comphenix.protocol.wrappers.Vector3F; +import com.jverbruggen.jrides.api.JRidesPlayerLocation; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.util.Vector; +import org.joml.Vector3f; + +import javax.annotation.Nullable; +import java.util.List; + +public class Vector3 { + private static final Vector3 ZERO = new Vector3(0,0,0); + + public double x; + public double y; + public double z; + + public Vector3() { + this.x = 0.0; + this.y = 0.0; + this.z = 0.0; + } + + public Vector3(Vector vector) { + this(vector.getX(), vector.getY(), vector.getZ()); + } + + public Vector3(double x, double y, double z) + { + this.x = x; + this.y = y; + this.z = z; + } + + public static Vector3 zero() { + return Vector3.ZERO; + } + + public double getX() { + return x; + } + + public double getY() { + return y; + } + + public double getZ() { + return z; + } + + public int getBlockX(){ + return (int) x; + } + + public int getBlockY(){ + return (int) y; + } + + public int getBlockZ(){ + return (int) z; + } + + public boolean isZero(){ + return x == 0 && y == 0 && z == 0; + } + + public Vector2 getXY() { + return new Vector2(x, y); + } + + public Vector2 getXZ() { + return new Vector2(x, z); + } + + /** + * Returns a new vector with the x/y/z values inverted. + * + * @return negated vector + */ + public Vector3 negate() { + return new Vector3(-x, -y, -z); + } + + public double length(){ + return Math.sqrt(x*x+y*y+z*z); + } + + /** + * Returns a new normalized vector of this vector (length = 1) + * + * @return normalized vector + */ + public Vector3 normalize() { + double len = this.length(); + return new Vector3((x/len), (y/len), (z/len)); + } + + public double distanceSquared(Vector3 v) { + double dx = (this.x - v.x); + double dy = (this.y - v.y); + double dz = (this.z - v.z); + return (dx * dx) + (dy * dy) + (dz * dz); + } + + @SuppressWarnings("MethodDoesntCallSuperMethod") + @Override + public Vector3 clone() { + return new Vector3(x, y, z); + } + + @Override + public String toString() { + return "{x=" + x + ", y=" + y + ", z=" + z + "}"; + } + + public String toShortString(){ + return "{" + ((double)(int)(this.x*10))/10 + ", " + ((double)(int)(this.y*10))/10 + ", " + ((double)(int)(this.z*10))/10 + "}"; + } + + public Vector toBukkitVector(){ + return new Vector(x, y, z); + } + + public Location toBukkitLocation(World world) { + return new Location(world, x, y, z); + } + + public Location toBukkitLocation(World world, double yaw) { + return new Location(world, x, y, z, (float)yaw, 0f); + } + + public Vector3F toVector3F(){ + float x = (float) this.x; + float y = (float) this.y; + float z = (float) this.z; + return new Vector3F(x, y, z); + } + + public Vector3f toVector3fJoml(){ + return new Vector3f((float) x, (float) y, (float) z); + } + + public Vector3 toBlock(){ + int blockX = this.getBlockX(); + int blockY = this.getBlockY(); + int blockZ = this.getBlockZ(); + return new Vector3(blockX, blockY, blockZ); + } + + public boolean equals(Vector3 p) { + return p.x == x && p.y == y && p.z == z; + } + + public static Vector3 multiply(Vector3 v, double multiplication){ + return new Vector3( + v.x * multiplication, + v.y * multiplication, + v.z * multiplication + ); + } + + /** + * Returns the cross product of two vectors + * + * @param v1 first vector + * @param v2 second vector + * @return cross product + */ + public static Vector3 cross(Vector3 v1, Vector3 v2) { + return new Vector3( + v1.y*v2.z - v1.z*v2.y, + v2.x*v1.z - v2.z*v1.x, + v1.x*v2.y - v1.y*v2.x + ); + } + + /** + * Returns the vector subtraction of two vectors (v1 - v2) + * + * @param v1 + * @param v2 + * @return subtracted vector + */ + public static Vector3 subtract(Vector3 v1, Vector3 v2) { + return new Vector3( + v1.x - v2.x, + v1.y - v2.y, + v1.z - v2.z + ); + } + + public static Vector3 add(Vector3 v1, Vector3 v2) { + return new Vector3( + v1.x + v2.x, + v1.y + v2.y, + v1.z + v2.z + ); + } + + /** + * Returns the vector average of two vectors ((v1 + v2) / 2) + * + * @param v1 + * @param v2 + * @return average vector + */ + public static Vector3 average(Vector3 v1, Vector3 v2) { + return new Vector3( + (v1.x + v2.x) / 2.0f, + (v1.y + v2.y) / 2.0f, + (v1.z + v2.z) / 2.0f + ); + } + + /** + * Returns the vector average of three vectors ((v1 + v2 + v3) / 3) + * + * @param v1 + * @param v2 + * @param v3 + * @return average vector + */ + public static Vector3 average(Vector3 v1, Vector3 v2, Vector3 v3) { + return new Vector3( + (v1.x + v2.x + v3.x) / 3.0f, + (v1.y + v2.y + v3.y) / 3.0f, + (v1.z + v2.z + v3.z) / 3.0f + ); + } + + /** + * Returns the vector average of four vectors ((v1 + v2 + v3 + v4) / 4) + * + * @param v1 + * @param v2 + * @param v3 + * @param v4 + * @return average vector + */ + public static Vector3 average(Vector3 v1, Vector3 v2, Vector3 v3, Vector3 v4) { + return new Vector3( + (v1.x + v2.x + v3.x + v4.x) / 4.0f, + (v1.y + v2.y + v3.y + v4.y) / 4.0f, + (v1.z + v2.z + v3.z + v4.z) / 4.0f + ); + } + + /** + * Returns the vector dot product of two vectors (v1 . v2) + * + * @param v1 + * @param v2 + * @return vector dot product + */ + public static double dot(Vector3 v1, Vector3 v2) { + return (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); + } + + public static Vector3 fromDoubleList(List doubleList){ + if(doubleList == null) return null; + if(doubleList.size() != 3) throw new RuntimeException("Can only create vector from double list of length 3"); + return new Vector3(doubleList.get(0), doubleList.get(1), doubleList.get(2)); + } + + public static Vector3 fromBukkitLocation(@Nullable Location bukkitLocation) { + if(bukkitLocation == null) return null; + return new Vector3(bukkitLocation.getX(), bukkitLocation.getY(), bukkitLocation.getZ()); + } + + public static boolean chunkRotated(Vector3 v1, Vector3 v2, int chunkSize){ + boolean xModRotated = (int)(v2.getX() / chunkSize) != (int)(v1.getX() / chunkSize); + boolean yModRotated = (int)(v2.getY() / chunkSize) != (int)(v1.getY() / chunkSize); + boolean zModRotated = (int)(v2.getZ() / chunkSize) != (int)(v1.getZ() / chunkSize); + + return xModRotated || yModRotated || zModRotated; + } + + public static boolean chunkRotated(Location l1, Location l2, int chunkSize){ + boolean xModRotated = (int)(l2.getX() / chunkSize) != (int)(l1.getX() / chunkSize); + boolean yModRotated = (int)(l2.getY() / chunkSize) != (int)(l1.getY() / chunkSize); + boolean zModRotated = (int)(l2.getZ() / chunkSize) != (int)(l1.getZ() / chunkSize); + + return xModRotated || yModRotated || zModRotated; + } + + public static Vector3 fromPlayerLocation(JRidesPlayerLocation playerLocation){ + return new Vector3(playerLocation.getX(), playerLocation.getY(), playerLocation.getZ()); + } + + public void setTo(Vector3 other) { + this.x = other.x; + this.y = other.y; + this.z = other.z; + } +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/models/math/Vector3PlusYaw.java b/src/main/java/com/jverbruggen/jrides/models/math/Vector3PlusYaw.java new file mode 100644 index 00000000..9637b903 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/math/Vector3PlusYaw.java @@ -0,0 +1,56 @@ +package com.jverbruggen.jrides.models.math; + +import com.jverbruggen.jrides.api.JRidesPlayerLocation; +import org.bukkit.util.Vector; + +import java.util.List; + +public class Vector3PlusYaw extends Vector3 { + private static final Vector3PlusYaw ZERO = new Vector3PlusYaw(0,0,0,0); + + public double yaw; + + public Vector3PlusYaw() { + super(); + this.yaw = 0.0; + } + + public Vector3PlusYaw(Vector vector) { + this(vector.getX(), vector.getY(), vector.getZ(), 0.0); + } + + public Vector3PlusYaw(double x, double y, double z, double yaw) + { + this.x = x; + this.y = y; + this.z = z; + this.yaw = yaw; + } + + public static Vector3PlusYaw zero() { + return Vector3PlusYaw.ZERO; + } + + public double getYaw() { + return yaw; + } + + public void setYaw(double yaw) { + this.yaw = yaw; + } + + public static Vector3PlusYaw fromDoubleList(List doubleList){ + if(doubleList == null) return null; + if(doubleList.size() == 3){ + return new Vector3PlusYaw(doubleList.get(0), doubleList.get(1), doubleList.get(2), 0.0); + }else if(doubleList.size() == 4){ + return new Vector3PlusYaw(doubleList.get(0), doubleList.get(1), doubleList.get(2), doubleList.get(3)); + } + + throw new RuntimeException("Can only create vector+yaw from double list of length 3 or 4"); + } + + public static Vector3PlusYaw fromPlayerLocation(JRidesPlayerLocation playerLocation){ + return new Vector3PlusYaw(playerLocation.getX(), playerLocation.getY(), playerLocation.getZ(), playerLocation.getYaw()); + } +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/models/math/Vector4.java b/src/main/java/com/jverbruggen/jrides/models/math/Vector4.java new file mode 100644 index 00000000..9fbb3d27 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/math/Vector4.java @@ -0,0 +1,28 @@ +package com.jverbruggen.jrides.models.math; + +public class Vector4 { + public double x; + public double y; + public double z; + public double w; + + public Vector4() { + this.x = 0.0; + this.y = 0.0; + this.z = 0.0; + this.w = 0.0; + } + + public Vector4(double x, double y, double z, double w) + { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + + @Override + public String toString() { + return "{x=" + x + ", y=" + y + ", z=" + z + ", w=" + w + "}"; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/math/VectorQuaternionState.java b/src/main/java/com/jverbruggen/jrides/models/math/VectorQuaternionState.java new file mode 100644 index 00000000..b4e8bd80 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/math/VectorQuaternionState.java @@ -0,0 +1,23 @@ +package com.jverbruggen.jrides.models.math; + +public class VectorQuaternionState { + private final Vector3 vector; + private final Quaternion quaternion; + + public VectorQuaternionState(Vector3 vector, Quaternion quaternion) { + this.vector = vector.clone(); + this.quaternion = quaternion.clone(); + } + + public Vector3 getVector() { + return vector; + } + + public Quaternion getQuaternion() { + return quaternion; + } + + public static VectorQuaternionState zero(){ + return new VectorQuaternionState(new Vector3(), new Quaternion()); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/menu/BaseMenu.java b/src/main/java/com/jverbruggen/jrides/models/menu/BaseMenu.java new file mode 100644 index 00000000..bfd07e16 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/menu/BaseMenu.java @@ -0,0 +1,63 @@ +package com.jverbruggen.jrides.models.menu; + +import com.jverbruggen.jrides.api.JRidesPlayer; +import org.bukkit.Bukkit; +import org.bukkit.inventory.Inventory; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public abstract class BaseMenu implements Menu { + private final HashMap buttons; + private final Map sessions; + private final int inventoryRows; + private final String inventoryTitle; + + public BaseMenu(int inventoryRows, String inventoryTitle) { + this.inventoryRows = inventoryRows; + this.inventoryTitle = inventoryTitle; + this.buttons = new HashMap<>(); + this.sessions = new HashMap<>(); + } + + public Map getSessions() { + return sessions; + } + + public void addSession(JRidesPlayer player, Inventory inventory){ + sessions.put(player, inventory); + } + + public void removeSession(JRidesPlayer player){ + sessions.remove(player); + } + + public Inventory getInventoryFor(JRidesPlayer player){ + Inventory inventory = Bukkit.createInventory(player.getBukkitPlayer(), 9*inventoryRows, inventoryTitle); + + for(MenuButton button : buttons.values()){ + inventory.setItem(button.getSlot(), button.getItemStack()); + } + + return inventory; + } + + @Override + public Menu addButton(MenuButton button) { + buttons.put(button.getUuid(), button); + button.setParentMenu(this); + return this; + } + + public MenuButton getButton(UUID buttonUUID){ + return buttons.get(buttonUUID); + } + + @Override + public void sendUpdate() { + buttons.values().forEach(MenuButton::sendUpdate); + } + + +} diff --git a/src/main/java/com/jverbruggen/jrides/models/menu/ButtonVisual.java b/src/main/java/com/jverbruggen/jrides/models/menu/ButtonVisual.java new file mode 100644 index 00000000..4293edf9 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/menu/ButtonVisual.java @@ -0,0 +1,19 @@ +package com.jverbruggen.jrides.models.menu; + +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +public interface ButtonVisual { + ChatColor getButtonDisplayNameColor(); + Material getButtonMaterial(); + String getValue(); + ItemStack toItemStack(); + boolean update(); + boolean hasUpdate(); + List getLore(); + void clearUpdate(); + boolean needsFullItemStackReload(); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/menu/Menu.java b/src/main/java/com/jverbruggen/jrides/models/menu/Menu.java new file mode 100644 index 00000000..19fb24c0 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/menu/Menu.java @@ -0,0 +1,19 @@ +package com.jverbruggen.jrides.models.menu; + +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.models.entity.Player; +import org.bukkit.inventory.Inventory; + +import java.util.Map; +import java.util.UUID; + +public interface Menu { + Map getSessions(); + void addSession(JRidesPlayer player, Inventory inventory); + void removeSession(JRidesPlayer player); + + Inventory getInventoryFor(JRidesPlayer player); + Menu addButton(MenuButton button); + MenuButton getButton(UUID buttonUUID); + void sendUpdate(); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/menu/MenuButton.java b/src/main/java/com/jverbruggen/jrides/models/menu/MenuButton.java new file mode 100644 index 00000000..3181c411 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/menu/MenuButton.java @@ -0,0 +1,42 @@ +package com.jverbruggen.jrides.models.menu; + +import com.jverbruggen.jrides.models.entity.Player; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.UUID; + +public interface MenuButton { + void sendUpdate(); + + void changeDisplayName(String displayName); + + void changeMaterial(Material material); + + void changeTitleColor(ChatColor color); + + void changeLore(List lore); + + ItemStack getItemStack(); + + void setItemStack(ItemStack itemStack); + + void setVisible(boolean visible); + + void setParentMenu(Menu parentMenu); + + Menu getParentMenu(); + + UUID getUuid(); + + int getSlot(); + + void press(Player player); + + ButtonVisual getActiveVisual(); + void updateVisual(); + Sound getPressedSound(); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/menu/MenuButtonAction.java b/src/main/java/com/jverbruggen/jrides/models/menu/MenuButtonAction.java new file mode 100644 index 00000000..9914b62c --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/menu/MenuButtonAction.java @@ -0,0 +1,7 @@ +package com.jverbruggen.jrides.models.menu; + +import com.jverbruggen.jrides.models.entity.Player; + +public interface MenuButtonAction { + void run(Player player, MenuButton button); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/menu/SimpleMenu.java b/src/main/java/com/jverbruggen/jrides/models/menu/SimpleMenu.java new file mode 100644 index 00000000..18262fe0 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/menu/SimpleMenu.java @@ -0,0 +1,7 @@ +package com.jverbruggen.jrides.models.menu; + +public class SimpleMenu extends BaseMenu { + public SimpleMenu(int inventoryRows, String inventoryTitle) { + super(inventoryRows, inventoryTitle); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/menu/SimpleMenuButton.java b/src/main/java/com/jverbruggen/jrides/models/menu/SimpleMenuButton.java new file mode 100644 index 00000000..1debf831 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/menu/SimpleMenuButton.java @@ -0,0 +1,175 @@ +package com.jverbruggen.jrides.models.menu; + +import com.jverbruggen.jrides.models.entity.Player; +import de.tr7zw.nbtapi.NBTItem; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.List; +import java.util.UUID; + +public class SimpleMenuButton implements MenuButton { + private final ButtonVisual buttonVisual; + private ItemStack itemStack; + private int slot; + private UUID uuid; + private MenuButtonAction action; + private Menu parentMenu; + private boolean visible; + private boolean hasUpdate; + + public SimpleMenuButton(ButtonVisual visual, int slot, MenuButtonAction action) { + this.slot = slot; + this.action = action; + this.visible = true; + this.hasUpdate = false; + this.buttonVisual = visual; + + this.uuid = UUID.randomUUID(); + setItemStack(visual.toItemStack()); + } + + @Override + public void sendUpdate(){ + if(buttonVisual.hasUpdate()){ + setButtonVisual(buttonVisual); + } + + if(hasUpdate){ + hasUpdate = false; + + getParentMenu().getSessions().forEach((player, inventory) -> inventory.setItem(slot, getItemStack())); + } + } + + @Override + public void changeDisplayName(String displayName){ + ItemStack newItemStack = itemStack.clone(); + ItemMeta itemMeta = newItemStack.getItemMeta(); + + assert itemMeta != null; + itemMeta.setDisplayName(displayName); + newItemStack.setItemMeta(itemMeta); + + itemStack = newItemStack; + + hasUpdate = true; + } + + @Override + public void changeMaterial(Material material){ + if(itemStack.getType() == material) return; + + ItemStack newItemStack = itemStack.clone(); + newItemStack.setType(material); + + itemStack = newItemStack; + + hasUpdate = true; + } + + @Override + public void changeTitleColor(ChatColor color){ + String displayName = itemStack.getItemMeta().getDisplayName(); + displayName = ChatColor.stripColor(displayName); + changeDisplayName(color + displayName); + } + + @Override + public void changeLore(List lore){ + ItemStack newItemStack = itemStack.clone(); + ItemMeta itemMeta = newItemStack.getItemMeta(); + + itemMeta.setLore(lore); + newItemStack.setItemMeta(itemMeta); + + itemStack = newItemStack; + + hasUpdate = true; + } + + @Override + public ItemStack getItemStack(){ + if(!visible) return null; + + return itemStack; + } + + @Override + public void setItemStack(ItemStack itemStack) { + NBTItem nbtItem = new NBTItem(itemStack); + nbtItem.setString(BUTTON_UUID_KEY, uuid.toString()); + + this.itemStack = nbtItem.getItem(); + + hasUpdate = true; + } + + @Override + public void setVisible(boolean visible){ + this.visible = visible; + + hasUpdate = true; + } + + @Override + public void setParentMenu(Menu parentMenu) { + this.parentMenu = parentMenu; + } + + @Override + public Menu getParentMenu() { + return parentMenu; + } + + @Override + public UUID getUuid() { + return uuid; + } + + @Override + public int getSlot() { + return slot; + } + + @Override + public void press(Player player){ + if(action == null) return; + action.run(player, this); + player.playSound(getPressedSound()); + sendUpdate(); + } + + @Override + public ButtonVisual getActiveVisual() { + return buttonVisual; + } + + @Override + public void updateVisual() { + setItemStack(buttonVisual.toItemStack()); + } + + @Override + public Sound getPressedSound() { + return Sound.UI_BUTTON_CLICK; + } + + private void setButtonVisual(ButtonVisual visual){ + visual.clearUpdate(); + + if(visual.needsFullItemStackReload()){ + setItemStack(visual.toItemStack()); + return; + } + + changeMaterial(visual.getButtonMaterial()); + changeDisplayName(visual.getButtonDisplayNameColor() + visual.getValue()); + changeLore(visual.getLore()); + } + + public static String BUTTON_UUID_KEY = "jrides-button-uuid"; +} diff --git a/src/main/java/com/jverbruggen/jrides/models/message/ActionBarMessage.java b/src/main/java/com/jverbruggen/jrides/models/message/ActionBarMessage.java new file mode 100644 index 00000000..bf4786dd --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/message/ActionBarMessage.java @@ -0,0 +1,30 @@ +package com.jverbruggen.jrides.models.message; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.wrappers.EnumWrappers; +import com.comphenix.protocol.wrappers.WrappedChatComponent; +import com.jverbruggen.jrides.models.entity.Player; + +public class ActionBarMessage implements Message { + private ProtocolManager protocolManager; + private String contents; + + public ActionBarMessage(ProtocolManager protocolManager, String contents) { + this.protocolManager = protocolManager; + this.contents = contents; + } + + @Override + public void send(Player player) { + PacketContainer packet = new PacketContainer(PacketType.Play.Server.CHAT); + WrappedChatComponent wcc = WrappedChatComponent.fromJson("{\"text\": \"" + contents + "\"}"); + packet.getChatComponents() + .write(0, wcc); + packet.getChatTypes() + .write(0, EnumWrappers.ChatType.GAME_INFO); + + this.protocolManager.sendServerPacket(player.getBukkitPlayer(), packet); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/message/Message.java b/src/main/java/com/jverbruggen/jrides/models/message/Message.java new file mode 100644 index 00000000..a85fad31 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/message/Message.java @@ -0,0 +1,7 @@ +package com.jverbruggen.jrides.models.message; + +import com.jverbruggen.jrides.models.entity.Player; + +public interface Message { + void send(Player player); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/message/MessageFactory.java b/src/main/java/com/jverbruggen/jrides/models/message/MessageFactory.java new file mode 100644 index 00000000..e7999f73 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/message/MessageFactory.java @@ -0,0 +1,20 @@ +package com.jverbruggen.jrides.models.message; + +import com.comphenix.protocol.ProtocolManager; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; + +public class MessageFactory { + private ProtocolManager protocolManager; + + public MessageFactory() { + this.protocolManager = ServiceProvider.getSingleton(ProtocolManager.class); + } + + public Message getTitle(String title, String subtitle){ + return new TitleMessage(title, subtitle); + } + + public Message getActionBarMessage(String contents){ + return new ActionBarMessage(protocolManager, contents); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/message/TitleMessage.java b/src/main/java/com/jverbruggen/jrides/models/message/TitleMessage.java new file mode 100644 index 00000000..6119a60b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/message/TitleMessage.java @@ -0,0 +1,29 @@ +package com.jverbruggen.jrides.models.message; + +import com.jverbruggen.jrides.models.entity.Player; + +public class TitleMessage implements Message { + private String title; + private String subtitle; + private int fadeIn = 1; + private int stay = 5; + private int fadeOut = 1; + + public TitleMessage(String title, String subtitle) { + this.title = title; + this.subtitle = subtitle; + } + + public TitleMessage(String title, String subtitle, int fadeIn, int stay, int fadeOut) { + this.title = title; + this.subtitle = subtitle; + this.fadeIn = fadeIn; + this.stay = stay; + this.fadeOut = fadeOut; + } + + @Override + public void send(Player player) { + player.getBukkitPlayer().sendTitle(title, subtitle, fadeIn, stay, fadeOut); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/properties/DebounceCall.java b/src/main/java/com/jverbruggen/jrides/models/properties/DebounceCall.java new file mode 100644 index 00000000..24d6f26f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/properties/DebounceCall.java @@ -0,0 +1,30 @@ +package com.jverbruggen.jrides.models.properties; + +public class DebounceCall { + private final int allowEveryXCalls; + private int callState; + + public DebounceCall(int allowEveryXCalls) { + this.allowEveryXCalls = allowEveryXCalls; + } + + public boolean run(Runnable runnable){ + if(callState == 0) runnable.run(); + + if(callState < allowEveryXCalls){ + callState++; + return false; + }else{ + reset(); + return true; + } + } + + public boolean hasDebounceProgress(){ + return callState > 0; + } + + public void reset(){ + this.callState = 0; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/properties/LocRot.java b/src/main/java/com/jverbruggen/jrides/models/properties/LocRot.java new file mode 100644 index 00000000..da1f85d0 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/properties/LocRot.java @@ -0,0 +1,13 @@ +package com.jverbruggen.jrides.models.properties; + +import com.jverbruggen.jrides.models.math.Vector3; + +public record LocRot(Vector3 location, Vector3 rotation) { + + public static LocRot fromLocationRotation(Vector3 location, Vector3 rotation) { + if(location == null) throw new RuntimeException("Needs location to create LocRot"); + + if(rotation == null) rotation = Vector3.zero(); + return new LocRot(location, rotation); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/properties/MinMaxWaitingTimer.java b/src/main/java/com/jverbruggen/jrides/models/properties/MinMaxWaitingTimer.java new file mode 100644 index 00000000..783ce2b5 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/properties/MinMaxWaitingTimer.java @@ -0,0 +1,141 @@ +package com.jverbruggen.jrides.models.properties; + +import com.jverbruggen.jrides.control.DispatchLock; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.language.LanguageFileTag; +import com.jverbruggen.jrides.language.StringReplacementBuilder; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.ChatColor; + +import javax.annotation.Nonnull; +import java.util.List; +import java.util.function.Supplier; + +public class MinMaxWaitingTimer { + private final int minimumWaitingTime; + private final int maximumWaitingTime; + private final DispatchLock lock; + private final LanguageFile languageFile; + + private double preferredWaitingTime; + private double waitingTimerState; + private int waitingTimerInt; + private Supplier reachedTimeFunction; + + public MinMaxWaitingTimer(int minimumWaitingTime, int maximumWaitingTime, DispatchLock lock) { + this.minimumWaitingTime = minimumWaitingTime; + this.maximumWaitingTime = maximumWaitingTime; + this.lock = lock; + this.languageFile = ServiceProvider.getSingleton(LanguageFile.class); + this.reachedTimeFunction = this::reachedPreferred; + + reset(); + } + + public void setReachedTimeFunction(@Nonnull Supplier function){ + this.reachedTimeFunction = function; + } + + public boolean reachedMinimum(){ + return minimumWaitingTime <= waitingTimerState; + } + + public boolean reachedMaximum(){ + return maximumWaitingTime <= waitingTimerState; + } + + public boolean reachedPreferred() { + return preferredWaitingTime <= waitingTimerState; + } + + public boolean reachedFunction(){ + return reachedTimeFunction.get(); + } + + public void increment(long tickInterval){ + waitingTimerState += (double)tickInterval/20d; + + if(waitingTimerInt != (int)waitingTimerState){ + waitingTimerInt = (int) waitingTimerState; + sendStatusMessage(); + } + + if(reachedFunction()){ + this.lock.unlock(); + } + } + + public void reset(){ + waitingTimerState = 0d; + waitingTimerInt = 0; + preferredWaitingTime = minimumWaitingTime; + sendStatusMessage(); + + if(reachedFunction()) + this.lock.unlock(); + else + this.lock.lock(); + } + + private void sendStatusMessage(){ + this.lock.setStatus(waitingTimerInt + "s / " + (int)preferredWaitingTime + "s waited"); + } + + public int timeUntilMinimum(){ + return minimumWaitingTime - (int) waitingTimerState; + } + + public int timeUntilMaximum(){ + return maximumWaitingTime - (int) waitingTimerState; + } + + public double timeUntilPreferredWaitingTime(){ + return preferredWaitingTime - waitingTimerState; + } + + public void setPreferredWaitingTimeFromNow(int addTime){ + double newPreferredWaitingTime = waitingTimerState + addTime; + + if(newPreferredWaitingTime < minimumWaitingTime) newPreferredWaitingTime = minimumWaitingTime; + else if(newPreferredWaitingTime > maximumWaitingTime) newPreferredWaitingTime = maximumWaitingTime; + + preferredWaitingTime = newPreferredWaitingTime; + } + + public int getMinimumWaitingTime() { + return minimumWaitingTime; + } + + public int getMaximumWaitingTime() { + return maximumWaitingTime; + } + + public int getVisualDispatchTime(double timeUntil){ + if(timeUntil < 0) timeUntil = 0; + return (int) Math.ceil(timeUntil); + } + + public void sendTimeWaitingNotification(List players, int visualDispatchTime){ + if(visualDispatchTime <= 0){ + players.forEach(p -> p.sendActionbarMessage("")); + return; + } + + String waitingTimeNotification = new StringReplacementBuilder() + .add(LanguageFileTag.time, visualDispatchTime + "") + .apply(languageFile.get(LanguageFileField.NOTIFICATION_DISPATCH_WAIT_SPECIFIC)); + + players.forEach(p -> p.sendActionbarMessage(ChatColor.GOLD + waitingTimeNotification)); + } + + public void sendGenericWaitingNotification(List players){ + players.forEach(p -> p.sendActionbarMessage(ChatColor.GOLD + languageFile.get(LanguageFileField.NOTIFICATION_DISPATCH_WAIT_GENERIC))); + } + + @Override + public String toString() { + return ""; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/properties/PlayerLocation.java b/src/main/java/com/jverbruggen/jrides/models/properties/PlayerLocation.java new file mode 100644 index 00000000..e7a57a04 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/properties/PlayerLocation.java @@ -0,0 +1,80 @@ +package com.jverbruggen.jrides.models.properties; + +import com.jverbruggen.jrides.api.JRidesPlayerLocation; +import com.jverbruggen.jrides.models.math.Vector3; +import org.bukkit.Location; +import org.bukkit.World; + +import java.util.List; + +public class PlayerLocation implements JRidesPlayerLocation { + private double x; + private double y; + private double z; + private double yaw; + private double pitch; + + public PlayerLocation(double x, double y, double z, double yaw, double pitch) { + this.x = x; + this.y = y; + this.z = z; + this.yaw = yaw; + this.pitch = pitch; + } + + public double getX() { + return x; + } + + public double getY() { + return y; + } + + public double getZ() { + return z; + } + + public double getYaw() { + return yaw; + } + + public double getPitch() { + return pitch; + } + + public void setYaw(double yaw) { + this.yaw = yaw; + } + + public Vector3 toVector3(){ + return new Vector3(x,y,z); + } + + public Location toBukkitLocation(World world){ + return new Location(world, x, y, z, (float)yaw, (float)pitch); + } + + public static PlayerLocation fromDoubleList(List doubleList){ + if(doubleList == null) + return null; + if(doubleList.size() != 3 && doubleList.size() != 5) + return null; + + double x = doubleList.get(0); + double y = doubleList.get(1); + double z = doubleList.get(2); + double yaw = 0; + double pitch = 0; + + if(doubleList.size() == 5){ + yaw = doubleList.get(3); + pitch = doubleList.get(4); + } + + return new PlayerLocation(x, y, z, yaw, pitch); + } + + public static PlayerLocation fromVector3(Vector3 vector3){ + return new PlayerLocation(vector3.getX(), vector3.getY(), vector3.getZ(), 0, 0); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/properties/Speed.java b/src/main/java/com/jverbruggen/jrides/models/properties/Speed.java new file mode 100644 index 00000000..ae0bc3b8 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/properties/Speed.java @@ -0,0 +1,123 @@ +package com.jverbruggen.jrides.models.properties; + +import org.bukkit.Bukkit; + +public class Speed { + private static int FRACTIONAL_SPEED_COUNTER = 0; + private static final int FRAME_INCREMENT_FACTOR = 3; + + private double speedPerTick; + private boolean inverted; + + public Speed(double speed) { + this.speedPerTick = speed; + this.inverted = false; + } + + public Speed(double speed, boolean inverted) { + this.speedPerTick = speed; + this.inverted = inverted; + } + + public void setSpeed(double newSpeedPerTick){ + if(inverted) newSpeedPerTick = -newSpeedPerTick; + this.speedPerTick = newSpeedPerTick; + } + + public double getSpeedPerTick() { + if(inverted) return -speedPerTick; + return speedPerTick; + } + + public void add(double speed){ + this.speedPerTick += speed; + } + + public void add(double speed, double until){ + add(speed); + + if(this.speedPerTick > until) + this.speedPerTick = until; + } + + public void approach(double acceleration, double deceleration, double approachSpeed){ + if(this.speedPerTick > approachSpeed){ + minus(deceleration, approachSpeed); + }else if(this.speedPerTick < approachSpeed){ + add(acceleration, approachSpeed); + } + } + + public void minus(double speed){ + add(-speed); + } + + public void minus(double speed, double until){ + minus(speed); + if(this.speedPerTick < until) this.speedPerTick = until; + } + + public void multiply(double speed){ + this.speedPerTick *= speed; + } + + private int getFractionalFrameIncrement(double frameIncrement){ // 0.9 + int enlargedIncrement = (int) (FRACTIONAL_SPEED_COUNTER * frameIncrement * 100d); // 90 + + if(enlargedIncrement % 100 > (frameIncrement * 100d)) + return 0; + else + return 1; + } + + public int getFrameIncrement(){ + final double speedPerTick = getSpeedPerTick(); + + double frameIncrement = speedPerTick * FRAME_INCREMENT_FACTOR; + if(0.2 < frameIncrement && frameIncrement < 1){ + frameIncrement = getFractionalFrameIncrement(frameIncrement); + }else if(-1 < frameIncrement && frameIncrement < -0.2){ + frameIncrement = -getFractionalFrameIncrement(frameIncrement); + } + + return (int) frameIncrement; + } + + @SuppressWarnings("MethodDoesntCallSuperMethod") + public Speed clone(){ + return new Speed(this.speedPerTick, this.inverted); + } + + public boolean isZero(){ + return this.speedPerTick == 0; + } + + public boolean isPositive(){ + return this.speedPerTick >= 0; + } + + public void setInverted(boolean inverted) { +// Bukkit.broadcastMessage("Set SPD inverted " + inverted); + this.inverted = inverted; + } + + public boolean isInverted() { + return inverted; + } + + public boolean isGoingForwards(){ + return isPositive() && !isInverted(); + } + + @Override + public String toString() { + String invertedFlag = inverted ? " [I]" : ""; + return speedPerTick + "b/t" + invertedFlag; + } + + public static void incrementFractionalSpeedCounter(){ + FRACTIONAL_SPEED_COUNTER++; + if(FRACTIONAL_SPEED_COUNTER >= 1000) + FRACTIONAL_SPEED_COUNTER = 0; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/properties/TrackEnd.java b/src/main/java/com/jverbruggen/jrides/models/properties/TrackEnd.java new file mode 100644 index 00000000..ae230e49 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/properties/TrackEnd.java @@ -0,0 +1,6 @@ +package com.jverbruggen.jrides.models.properties; + +public enum TrackEnd { + START, + END +} diff --git a/src/main/java/com/jverbruggen/jrides/models/properties/TrainEnd.java b/src/main/java/com/jverbruggen/jrides/models/properties/TrainEnd.java new file mode 100644 index 00000000..6b63b466 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/properties/TrainEnd.java @@ -0,0 +1,5 @@ +package com.jverbruggen.jrides.models.properties; + +public enum TrainEnd { + HEAD, TAIL +} diff --git a/src/main/java/com/jverbruggen/jrides/models/properties/frame/AutoTrackUpdateFrame.java b/src/main/java/com/jverbruggen/jrides/models/properties/frame/AutoTrackUpdateFrame.java new file mode 100644 index 00000000..1bc6e588 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/properties/frame/AutoTrackUpdateFrame.java @@ -0,0 +1,147 @@ +package com.jverbruggen.jrides.models.properties.frame; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.logging.LogType; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.section.Section; +import org.bukkit.Bukkit; + +public class AutoTrackUpdateFrame implements Frame { + private int value; + private Track track; + private Section section; + private boolean invertFrameAddition; + + public AutoTrackUpdateFrame(int frame, Track track, Section section) { + this(frame, track, section, false); + } + + public AutoTrackUpdateFrame(int frame, Track track, Section section, boolean invertFrameAddition) { + this.value = frame; + this.track = track; + this.section = section; + this.invertFrameAddition = invertFrameAddition; + + updateTrack(frame); + } + + @Override + public int getValue() { + return value; + } + + @Override + public String getValueString() { + return String.valueOf(getValue()); + } + + @Override + public void setValue(int frame) { + this.value = frame; + } + + @Override + public Track getTrack() { + return track; + } + + @Override + public void setTrack(Track track) { + if(track == this.track) return; + + this.track = track; + } + + @Override + public Section getSection() { + return section; + } + + @Override + public void setSection(Section section) { + this.section = section; + + JRidesPlugin.getLogger().info(LogType.SECTIONS, "Updated frame " + this + " to section " + section); + + if(section.getParentTrack() != this.getTrack()){ + setTrack(section.getParentTrack()); + } + } + + @Override + public Frame add(int frames){ + if(invertFrameAddition) frames = -frames; + return addRaw(frames); + } + + private Frame addRaw(int frames){ + int newFrame = this.value + frames; + return updateTrack(newFrame); + } + + private Frame updateTrack(int toFrame){ + if(toFrame > track.getUpperFrame()){ // Going forwards and out of bounds + setValue(getTrack().getLowerFrame()); + return addRaw(toFrame - track.getUpperFrame()); + }else if(toFrame < track.getLowerFrame()){ // Going backwards and out of bounds + setValue(getTrack().getUpperFrame()); + return addRaw(toFrame - track.getLowerFrame()); + }else{ // Within bounds + setValue(toFrame); + return this; + } + } + + @SuppressWarnings("MethodDoesntCallSuperMethod") + @Override + public Frame clone(){ + return new AutoTrackUpdateFrame(value, track, section, invertFrameAddition); + } + + @Override + public Frame capture() { + return clone(); + } + + @Override + public void setInvertedFrameAddition(boolean inverted) { + JRidesPlugin.getLogger().info(LogType.SECTIONS, "Set inverted frame addition " + inverted); + invertFrameAddition = inverted; + } + + @Override + public boolean isInvertedFrameAddition() { + return invertFrameAddition; + } + + @Override + public void updateTo(Frame other){ + setValue(other.getValue()); + + Track otherTrack = other.getTrack(); + Section otherSection = other.getSection(); + if(otherTrack != null && otherTrack != this.getTrack()) setTrack(otherTrack); + if(otherSection != null && otherSection != this.getSection()) setSection(otherSection); + } + + @Override + public String toString() { + String invertedTag = ""; + if(invertFrameAddition) invertedTag = " [invert] "; + return ""; + } + + public boolean equals(Frame other) { + return this.getValue() == other.getValue(); + } + + @Override + public boolean equals(Object obj) { + if(obj instanceof Frame) return equals((Frame) obj); + return super.equals(obj); + } + + public static AutoTrackUpdateFrame of(Frame frame){ + return new AutoTrackUpdateFrame(frame.getValue(), frame.getTrack(), frame.getSection()); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/properties/frame/CyclicFrame.java b/src/main/java/com/jverbruggen/jrides/models/properties/frame/CyclicFrame.java new file mode 100644 index 00000000..f7072729 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/properties/frame/CyclicFrame.java @@ -0,0 +1,95 @@ +package com.jverbruggen.jrides.models.properties.frame; + +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.section.Section; + +public class CyclicFrame implements Frame { + private int frame; + private final int cycle; + private Track track; + private Section section; + + public CyclicFrame(int frame, int cycle, Track track, Section section) { + this.frame = frame; + this.cycle = cycle; + this.track = track; + this.section = section; + } + + @Override + public int getValue() { + return frame; + } + + @Override + public String getValueString() { + return String.valueOf(getValue()); + } + + @Override + public void setValue(int frame) { + this.frame = Frame.getCyclicFrameValue(frame, cycle); + } + + @Override + public Track getTrack() { + return track; + } + + @Override + public void setTrack(Track track) { + this.track = track; + } + + @Override + public Section getSection() { + return section; + } + + @Override + public void setSection(Section section) { + this.section = section; + } + + @Override + public Frame add(int frames) { + setValue(this.frame + frames); + return this; + } + + @SuppressWarnings("MethodDoesntCallSuperMethod") + @Override + public Frame clone() { + return new CyclicFrame(frame, cycle, track, section); + } + + @Override + public Frame capture() { + return clone(); + } + + @Override + public void setInvertedFrameAddition(boolean inverted) { + throw new RuntimeException("Not supported"); + } + + @Override + public boolean isInvertedFrameAddition() { + return false; + } + + @Override + public void updateTo(Frame other) { + setValue(other.getValue()); + } + + @Override + public String toString() { + return ""; + } +// +// public static CyclicFrame fromFrame(Frame frame, int cycle){ +// int value = Frame.getCyclicFrameValue(frame.getValue(), cycle); +// return new CyclicFrame(value, cycle); +// } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/properties/frame/Frame.java b/src/main/java/com/jverbruggen/jrides/models/properties/frame/Frame.java new file mode 100644 index 00000000..13bf512c --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/properties/frame/Frame.java @@ -0,0 +1,53 @@ +package com.jverbruggen.jrides.models.properties.frame; + +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.section.Section; + +public interface Frame { + int getValue(); + String getValueString(); + + void setValue(int frame); + + Track getTrack(); + void setTrack(Track track); + + Section getSection(); + void setSection(Section section); + + Frame add(int frames); + Frame clone(); + Frame capture(); + + void setInvertedFrameAddition(boolean inverted); + boolean isInvertedFrameAddition(); + void updateTo(Frame other); + + static int getCyclicFrameValue(int nonCyclicFrame, int totalFrames){ + return Math.floorMod(nonCyclicFrame, totalFrames); + } + + static boolean isBetweenFrames(Frame lowerFrame, Frame upperFrame, Frame compareFrame){ + int lowerFrameValue = lowerFrame.getValue(); + int upperFrameValue = upperFrame.getValue(); + int compareFrameValue = compareFrame.getValue(); + + boolean inNormalSection = (lowerFrameValue < upperFrameValue) + && (lowerFrameValue <= compareFrameValue && compareFrameValue <= upperFrameValue); + boolean inCycledSection = (upperFrameValue < lowerFrameValue) + && (lowerFrameValue <= compareFrameValue || compareFrameValue <= upperFrameValue); + + return inNormalSection || inCycledSection; + } + + static Frame getDistanceFromUpperFrame(Frame lowerFrame, Frame upperFrame, int distanceFromUpperFrame){ + if(lowerFrame.getValue() >= upperFrame.getValue()) + return upperFrame.clone(); + + Frame calculatedDistanceFromUpperFrame = upperFrame.clone().add(-distanceFromUpperFrame); + if(calculatedDistanceFromUpperFrame.getValue() < lowerFrame.getValue()) + return lowerFrame.clone(); + + return calculatedDistanceFromUpperFrame; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/properties/frame/FrameRange.java b/src/main/java/com/jverbruggen/jrides/models/properties/frame/FrameRange.java new file mode 100644 index 00000000..655cf6cc --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/properties/frame/FrameRange.java @@ -0,0 +1,44 @@ +package com.jverbruggen.jrides.models.properties.frame; + +import com.jverbruggen.jrides.models.properties.frame.factory.FrameFactory; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; + +public class FrameRange { + private final Frame lower; + private final Frame upper; + private final int cycle; + + public FrameRange(Frame lower, Frame upper, int cycle) { + this.lower = lower; + this.upper = upper; + this.cycle = cycle; + } + + public Frame getInBetween(double percentage){ + int lowerValue = lower.getValue(); + int upperValue = upper.getValue(); + + int frameIndex; + if(lowerValue < upperValue){ + int delta = upperValue-lowerValue; + frameIndex = (int) (lowerValue+(delta*percentage)); + } + else { + int lowerValuePart = cycle - lowerValue; + int upperValuePart = upperValue; + int totalParts = lowerValuePart + upperValuePart; + double distribution = (double)lowerValuePart / (double)totalParts; + if(percentage > distribution){ + // = (0.8 - 0.6 ) / 0.4 = 0.5 (50%) + double upperPartPercentage = (percentage - distribution) / upperValuePart; + frameIndex = (int) (upperValue*upperPartPercentage); + }else{ + // = 0.4 / 0.6 = 0.66 (66%) + double lowerPartPercentage = percentage / distribution; + frameIndex = (int) (lowerValue + (lowerValuePart * lowerPartPercentage)); + } + } + + return ServiceProvider.getSingleton(FrameFactory.class).getBlankStaticFrame(frameIndex); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/properties/frame/LinkedFrame.java b/src/main/java/com/jverbruggen/jrides/models/properties/frame/LinkedFrame.java new file mode 100644 index 00000000..19f3e410 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/properties/frame/LinkedFrame.java @@ -0,0 +1,92 @@ +package com.jverbruggen.jrides.models.properties.frame; + +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.section.Section; + +public class LinkedFrame implements Frame { + private final Frame linkedTo; + private final int offsetFromLink; + private Section section; + private boolean canSetValue; + + public LinkedFrame(Frame linkedTo, int offsetFromLink, Section section) { + this.linkedTo = linkedTo; + this.offsetFromLink = offsetFromLink; + this.section = section; + this.canSetValue = true; + } + + @Override + public int getValue() { + return linkedTo.clone().add(offsetFromLink).getValue(); + } + + @Override + public String getValueString() { + return String.valueOf(getValue()); + } + + @Override + public void setValue(int frame) { + if(!canSetValue) + throw new RuntimeException("Cannot set value of this linked frame " + this); + linkedTo.setValue(frame - offsetFromLink); + } + + @Override + public Track getTrack() { + return linkedTo.getTrack(); + } + + @Override + public void setTrack(Track track) { + linkedTo.setTrack(track); + } + + @Override + public Section getSection() { + throw new RuntimeException("LinkedFrames dont have accurate sections"); + } + + @Override + public void setSection(Section section) { + this.section = section; + } + + @Override + public Frame add(int frames) { + linkedTo.add(frames); + return this; + } + + @SuppressWarnings("MethodDoesntCallSuperMethod") + @Override + public Frame clone() { + return new LinkedFrame(linkedTo, offsetFromLink, section); + } + + @Override + public Frame capture() { + return new LinkedFrame(linkedTo.capture(), offsetFromLink, section); + } + + @Override + public void setInvertedFrameAddition(boolean inverted) { + throw new RuntimeException("Not supported"); + } + + @Override + public boolean isInvertedFrameAddition() { + return false; + } + + @Override + public void updateTo(Frame other) { + setValue(other.getValue()); + } + + @Override + public String toString() { + return ""; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/properties/frame/SimpleFrame.java b/src/main/java/com/jverbruggen/jrides/models/properties/frame/SimpleFrame.java new file mode 100644 index 00000000..9db954b3 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/properties/frame/SimpleFrame.java @@ -0,0 +1,107 @@ +package com.jverbruggen.jrides.models.properties.frame; + +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.section.Section; + +public class SimpleFrame implements Frame { + private int frame; + private Track track; + private Section section; + + public SimpleFrame(int frame, Track track, Section section) { + this.frame = frame; + this.track = track; + this.section = section; + } + + public SimpleFrame(int frame) { + this.frame = frame; + } + + public SimpleFrame(int frame, Track track) { + this.frame = frame; + this.track = track; + } + + @Override + public int getValue() { + return frame; + } + + @Override + public String getValueString() { + return String.valueOf(getValue()); + } + + @Override + public void setValue(int frame) { + this.frame = frame; + } + + @Override + public Track getTrack() { + return track; + } + + @Override + public void setTrack(Track track) { + this.track = track; + } + + @Override + public Section getSection() { + return section; + } + + @Override + public void setSection(Section section) { + this.section = section; + } + + @Override + public Frame add(int frames){ + this.frame += frames; + return this; + } + + @SuppressWarnings("MethodDoesntCallSuperMethod") + @Override + public Frame clone(){ + return new SimpleFrame(frame, track, section); + } + + @Override + public Frame capture() { + return clone(); + } + + @Override + public void setInvertedFrameAddition(boolean inverted) { + throw new RuntimeException("Not supported"); + } + + @Override + public boolean isInvertedFrameAddition() { + return false; + } + + @Override + public void updateTo(Frame other){ + this.frame = other.getValue(); + } + + @Override + public String toString() { + return ""; + } + + public boolean equals(Frame other) { + return this.getValue() == other.getValue(); + } + + @Override + public boolean equals(Object obj) { + if(obj instanceof Frame) return equals((Frame) obj); + return super.equals(obj); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/properties/frame/factory/FrameFactory.java b/src/main/java/com/jverbruggen/jrides/models/properties/frame/factory/FrameFactory.java new file mode 100644 index 00000000..b432df40 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/properties/frame/factory/FrameFactory.java @@ -0,0 +1,46 @@ +package com.jverbruggen.jrides.models.properties.frame.factory; + +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.frame.SimpleFrame; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.section.Section; +import com.jverbruggen.jrides.models.ride.section.provider.SectionProvider; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; + +public class FrameFactory { + private final SectionProvider sectionProvider; + + public FrameFactory() { + sectionProvider = ServiceProvider.getSingleton(SectionProvider.class); + } + + public SimpleFrame getStaticFrame(int frameIndex, Track track){ + if(track == null) + throw new RuntimeException("Track cannot be null"); + + SimpleFrame frame = new SimpleFrame(frameIndex, track); + Section section = sectionProvider.findSectionInBulk(frame, track.getSections()); + if(section == null) + throw new RuntimeException("Could not find section for static frame " + frameIndex); + + frame.setTrack(track); + frame.setSection(section); + + return frame; + } + + public SimpleFrame getBlankStaticFrame(int frameIndex){ + return new SimpleFrame(frameIndex); + } + + public Frame createFrameBetween(Frame a, Frame b, double percentage){ + assert percentage <= 1 && percentage >= 0; + + int aValue = a.getValue(); + int bValue = b.getValue(); + int delta = bValue - aValue; + int offset = (int) (delta * percentage); + + return new SimpleFrame(aValue + offset); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/render/BoxViewport.java b/src/main/java/com/jverbruggen/jrides/models/render/BoxViewport.java new file mode 100644 index 00000000..d3ca8f01 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/render/BoxViewport.java @@ -0,0 +1,19 @@ +package com.jverbruggen.jrides.models.render; + +import com.jverbruggen.jrides.models.math.Vector3; + +public class BoxViewport extends VirtualEntityViewport implements Viewport { + protected Vector3 lowerCorner; + protected Vector3 upperCorner; + + public BoxViewport(int maxRenderDistance, Vector3 lowerCorner, Vector3 upperCorner) { + super(maxRenderDistance); + this.lowerCorner = lowerCorner; + this.upperCorner = upperCorner; + } + + @Override + public boolean isInViewport(Vector3 location) { + return false; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/render/GlobalViewport.java b/src/main/java/com/jverbruggen/jrides/models/render/GlobalViewport.java new file mode 100644 index 00000000..24706989 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/render/GlobalViewport.java @@ -0,0 +1,14 @@ +package com.jverbruggen.jrides.models.render; + +import com.jverbruggen.jrides.models.math.Vector3; + +public class GlobalViewport extends VirtualEntityViewport implements Viewport { + public GlobalViewport(int maxRenderDistance) { + super(maxRenderDistance); + } + + @Override + public boolean isInViewport(Vector3 location) { + return true; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/render/RangeViewport.java b/src/main/java/com/jverbruggen/jrides/models/render/RangeViewport.java new file mode 100644 index 00000000..c9f2675f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/render/RangeViewport.java @@ -0,0 +1,21 @@ +package com.jverbruggen.jrides.models.render; + +import com.jverbruggen.jrides.models.math.Vector3; + +public class RangeViewport extends VirtualEntityViewport implements Viewport { + private Vector3 middle; + private double range; + + public RangeViewport(int maxRenderDistance, Vector3 middle, double range) { + super(maxRenderDistance); + this.middle = middle; + this.range = range; + } + + @Override + public boolean isInViewport(Vector3 location) { + double rangeSquared = range*range; + double distanceSquared = middle.distanceSquared(location); + return distanceSquared <= rangeSquared; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/render/Viewport.java b/src/main/java/com/jverbruggen/jrides/models/render/Viewport.java new file mode 100644 index 00000000..497c8607 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/render/Viewport.java @@ -0,0 +1,22 @@ +package com.jverbruggen.jrides.models.render; + +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Vector3; + +import java.util.List; + +public interface Viewport { + List getEntities(); + List getViewers(); + boolean isInViewport(Vector3 location); + void addViewer(Player player); + void removeViewer(Player player); + void updateFor(Player player, Vector3 playerLocation); + boolean hasViewer(Player player); + void addEntity(VirtualEntity virtualEntity); + void removeEntity(VirtualEntity virtualEntity); + void updateEntityViewers(VirtualEntity virtualEntity); + boolean hasEntity(VirtualEntity virtualEntity); + void flushDeadEntities(); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/render/VirtualEntityViewport.java b/src/main/java/com/jverbruggen/jrides/models/render/VirtualEntityViewport.java new file mode 100644 index 00000000..5f7e7652 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/render/VirtualEntityViewport.java @@ -0,0 +1,116 @@ +package com.jverbruggen.jrides.models.render; + +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Vector3; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public abstract class VirtualEntityViewport implements Viewport{ + protected List virtualEntities; + protected List viewers; + private final int maxRenderDistance; + + public VirtualEntityViewport(int maxRenderDistance) { + this.virtualEntities = new ArrayList<>(); + this.viewers = new ArrayList<>(); + this.maxRenderDistance = maxRenderDistance; + } + + @Override + public List getEntities() { + return virtualEntities; + } + + @Override + public List getViewers() { + return viewers; + } + + @Override + public void addViewer(Player player) { + if(hasViewer(player)) return; + viewers.add(player); + } + + @Override + public void removeViewer(Player player) { + if(!hasViewer(player)) return; + viewers.remove(player); + + for(VirtualEntity virtualEntity : virtualEntities){ + if(!virtualEntity.isViewer(player)) continue; // TODO: Same as this::removeEntity TODO + virtualEntity.despawnFor(player, true); + } + } + + @Override + public boolean hasViewer(Player player) { + return viewers.contains(player); + } + + @Override + public void addEntity(VirtualEntity virtualEntity) { + if(hasEntity(virtualEntity)) return; + + virtualEntities.add(virtualEntity); + updateEntityViewers(virtualEntity); +// virtualEntity.spawnForAll(viewers); + } + + @Override + public void removeEntity(VirtualEntity virtualEntity) { + if(!hasEntity(virtualEntity)) return; + + virtualEntities.remove(virtualEntity); + //TODO: Should it be despawned? What if player and viewport are in a different viewport as well? + } + + @Override + public boolean hasEntity(VirtualEntity virtualEntity) { + return virtualEntities.contains(virtualEntity); + } + + @Override + public void updateFor(Player player, Vector3 playerLocation) { + if(!hasViewer(player)) addViewer(player); + + for(VirtualEntity virtualEntity : virtualEntities){ + renderLogic(virtualEntity, player, playerLocation); + } + } + + @Override + public void updateEntityViewers(VirtualEntity virtualEntity) { + if(!hasEntity(virtualEntity)) addEntity(virtualEntity); + + for(Player player : viewers){ + renderLogic(virtualEntity, player, player.getLocation()); + } + } + + @Override + public void flushDeadEntities() { + virtualEntities = getEntities().stream() + .filter(VirtualEntity::isAlive) + .collect(Collectors.toList()); + } + + private void renderLogic(VirtualEntity virtualEntity, Player player, Vector3 playerLocation){ + double distanceSquared = virtualEntity.getLocation().distanceSquared(playerLocation); + if(player.isViewing(virtualEntity)){ + if(distanceSquared > maxRenderDistance*maxRenderDistance){ + virtualEntity.despawnFor(player, true); + player.removeViewing(virtualEntity); + } + } + else{ + if(distanceSquared <= maxRenderDistance*maxRenderDistance){ + virtualEntity.spawnFor(player); + player.addViewing(virtualEntity); + } + } + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/AbstractRide.java b/src/main/java/com/jverbruggen/jrides/models/ride/AbstractRide.java new file mode 100644 index 00000000..aca47ec7 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/AbstractRide.java @@ -0,0 +1,59 @@ +package com.jverbruggen.jrides.models.ride; + +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +public abstract class AbstractRide implements Ride { + private String identifier; + private String displayName; + private List displayDescription; + private ItemStack displayItem; + private PlayerLocation warpLocation; + private boolean canExitDuringRide; + + public AbstractRide(String identifier, String displayName, List displayDescription, ItemStack displayItem, PlayerLocation warpLocation, boolean canExitDuringRide) { + this.identifier = identifier; + this.displayName = displayName; + this.displayDescription = displayDescription; + this.displayItem = displayItem; + this.warpLocation = warpLocation; + this.canExitDuringRide = canExitDuringRide; + } + + @Override + public String getIdentifier() { + return identifier; + } + + @Override + public String getDisplayName() { + return displayName; + } + + @Override + public ItemStack getDisplayItem() { + return displayItem; + } + + @Override + public List getDisplayDescription() { + return displayDescription; + } + + @Override + public PlayerLocation getWarpLocation() { + return warpLocation; + } + + @Override + public boolean isLoaded() { + return true; + } + + @Override + public boolean canExitDuringRide() { + return canExitDuringRide; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/CoasterStationHandle.java b/src/main/java/com/jverbruggen/jrides/models/ride/CoasterStationHandle.java new file mode 100644 index 00000000..e0244b17 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/CoasterStationHandle.java @@ -0,0 +1,89 @@ +package com.jverbruggen.jrides.models.ride; + +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.effect.handle.train.TrainEffectTriggerHandle; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.properties.MinMaxWaitingTimer; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.coaster.train.Vehicle; +import com.jverbruggen.jrides.models.ride.gate.Gate; + +import java.util.List; + +public class CoasterStationHandle extends StationHandle { + private Train stationaryTrain; + private CoasterHandle coasterHandle; + + public CoasterStationHandle(CoasterHandle coasterHandle, String name, String shortName, TriggerContext triggerContext, + List entryGates, MinMaxWaitingTimer waitingTimer, List entryBlockingEffectTriggers, + List exitBlockingEffectTriggers, List exitEffectTriggers, + PlayerLocation ejectLocation){ + super(name, shortName, entryGates, ejectLocation, waitingTimer, triggerContext, entryBlockingEffectTriggers, exitBlockingEffectTriggers, exitEffectTriggers); + this.coasterHandle = coasterHandle; + this.stationaryTrain = null; + + coasterHandle.addStationHandle(this); + } + + public boolean hasTrain(){ + return stationaryTrain != null; + } + + public Train getStationaryTrain(){ + return stationaryTrain; + } + + public CoasterHandle getCoasterHandle() { + return coasterHandle; + } + + public void setStationaryTrain(Train train) { + if(train == null){ + if(this.stationaryTrain != null) + this.stationaryTrain.setStationaryAt(null); + this.stationaryTrain = null; + return; + } + + if(stationaryTrain != null) throw new RuntimeException("Two trains cannot be in the same station!"); + this.stationaryTrain = train; + train.setStationaryAt(this); + } + + @Override + public void closeRestraints(){ + if(stationaryTrain == null) return; + + if(stationaryTrain.getRestraintState()) return; + + stationaryTrain.setRestraintForAll(true); + getTriggerContext().getRestraintTrigger().getLock().setLocked(false); + } + + public void onPlayerEnter(Player player){ + int passengerCount = getStationaryTrain().getPassengers().size(); + if(passengerCount == 1){ + getCoasterHandle().getRideController().getControlMode().getWaitingTimer().setPreferredWaitingTimeFromNow(15); + } + } + + public boolean shouldEject(){ + return true; + } + + public boolean isExit(){ + return true; + } + + @Override + public boolean hasVehicle() { + return hasTrain(); + } + + @Override + public Vehicle getStationaryVehicle() { + return getStationaryTrain(); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/Ride.java b/src/main/java/com/jverbruggen/jrides/models/ride/Ride.java new file mode 100644 index 00000000..7a370f9f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/Ride.java @@ -0,0 +1,18 @@ +package com.jverbruggen.jrides.models.ride; + +import com.jverbruggen.jrides.api.JRidesRide; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +public interface Ride extends JRidesRide { + String getIdentifier(); + String getDisplayName(); + List getDisplayDescription(); + ItemStack getDisplayItem(); + + PlayerLocation getWarpLocation(); + boolean isLoaded(); + boolean canExitDuringRide(); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/RideType.java b/src/main/java/com/jverbruggen/jrides/models/ride/RideType.java new file mode 100644 index 00000000..29c45df5 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/RideType.java @@ -0,0 +1,6 @@ +package com.jverbruggen.jrides.models.ride; + +public enum RideType { + COASTER, + FLATRIDE +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/StationHandle.java b/src/main/java/com/jverbruggen/jrides/models/ride/StationHandle.java new file mode 100644 index 00000000..7f09316b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/StationHandle.java @@ -0,0 +1,117 @@ +package com.jverbruggen.jrides.models.ride; + +import com.jverbruggen.jrides.control.trigger.TriggerContext; +import com.jverbruggen.jrides.effect.handle.train.TrainEffectTriggerHandle; +import com.jverbruggen.jrides.models.properties.MinMaxWaitingTimer; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.coaster.train.Vehicle; +import com.jverbruggen.jrides.models.ride.gate.Gate; + +import java.util.List; + +public class StationHandle { + private String name; + private String shortName; + private final List entryGates; + private final PlayerLocation ejectLocation; + private final MinMaxWaitingTimer waitingTimer; + private TriggerContext triggerContext; + private final List entryBlockingEffectTriggers; + private final List exitBlockingEffectTriggers; + private final List exitEffectTriggers; + + public StationHandle(String name, String shortName, List entryGates, PlayerLocation ejectLocation, MinMaxWaitingTimer waitingTimer, TriggerContext triggerContext, List entryBlockingEffectTriggers, List exitBlockingEffectTriggers, List exitEffectTriggers) { + this.name = name; + this.shortName = shortName; + this.entryGates = entryGates; + this.ejectLocation = ejectLocation; + this.waitingTimer = waitingTimer; + this.triggerContext = triggerContext; + this.entryBlockingEffectTriggers = entryBlockingEffectTriggers; + this.exitBlockingEffectTriggers = exitBlockingEffectTriggers; + this.exitEffectTriggers = exitEffectTriggers; + + triggerContext.getRestraintTrigger().setStationHandle(this); + triggerContext.getGateTrigger().setStationHandle(this); + } + + public PlayerLocation getEjectLocation() { + return ejectLocation; + } + + public List getEntryGates() { + return entryGates; + } + + public TriggerContext getTriggerContext() { + return triggerContext; + } + + public String getName() { + return name; + } + + public String getShortName() { + return shortName; + } + + public void openEntryGates(){ + entryGates.forEach(Gate::open); + } + + public void closeEntryGates(){ + entryGates.forEach(Gate::close); + // TODO: teleport everyone awae + } + + public boolean areEntryGatesClosed(){ + return entryGates.stream().noneMatch(Gate::isOpen); + } + + public MinMaxWaitingTimer getWaitingTimer() { + return waitingTimer; + } + + public void closeRestraints() { + triggerContext.getRestraintTrigger().getLock().setLocked(false); + } + + public boolean hasVehicle(){ + throw new RuntimeException("Has vehicle is not implemented yet for non-coaster station handle"); + } + + public Vehicle getStationaryVehicle(){ + throw new RuntimeException("Get vehicle is not implemented yet for non-coaster station handle"); + } + + @Override + public String toString() { + return "StationHandle{" + + "name='" + name + '\'' + + ", shortName='" + shortName + '\'' + + '}'; + } + + public void runEntryEffectTriggers(Train train){ + if(entryBlockingEffectTriggers == null) return; + entryBlockingEffectTriggers.forEach(t -> t.executeForTrain(train)); + } + + public void runExitEffectTriggers(Train train){ + if(exitBlockingEffectTriggers != null) + exitBlockingEffectTriggers.forEach(t -> t.executeForTrain(train)); + if(exitEffectTriggers != null) + exitEffectTriggers.forEach(t -> t.executeForTrain(train)); + } + + public boolean entryEffectTriggersDone(){ + if(entryBlockingEffectTriggers == null) return true; + return entryBlockingEffectTriggers.stream().allMatch(t -> t.getTrainEffectTrigger().finishedPlaying()); + } + + public boolean exitEffectTriggersDone(){ + if(exitBlockingEffectTriggers == null) return true; + return exitBlockingEffectTriggers.stream().allMatch(t -> t.getTrainEffectTrigger().finishedPlaying()); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/UnloadedRide.java b/src/main/java/com/jverbruggen/jrides/models/ride/UnloadedRide.java new file mode 100644 index 00000000..29b70b36 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/UnloadedRide.java @@ -0,0 +1,49 @@ +package com.jverbruggen.jrides.models.ride; + +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +public class UnloadedRide implements Ride { + private String identifier; + + public UnloadedRide(String identifier) { + this.identifier = identifier; + } + + @Override + public String getIdentifier() { + return identifier; + } + + @Override + public String getDisplayName() { + return identifier; + } + + @Override + public List getDisplayDescription() { + return List.of(); + } + + @Override + public ItemStack getDisplayItem() { + return null; + } + + @Override + public PlayerLocation getWarpLocation() { + return null; + } + + @Override + public boolean isLoaded() { + return false; + } + + @Override + public boolean canExitDuringRide() { + return false; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/coaster/Coaster.java b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/Coaster.java new file mode 100644 index 00000000..ad4f3486 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/Coaster.java @@ -0,0 +1,11 @@ +package com.jverbruggen.jrides.models.ride.coaster; + +import com.jverbruggen.jrides.models.ride.Ride; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +import java.util.List; + +public interface Coaster extends Ride { + List getTrains(); + void addTrain(Train train); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/coaster/SimpleCoaster.java b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/SimpleCoaster.java new file mode 100644 index 00000000..2e79f219 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/SimpleCoaster.java @@ -0,0 +1,28 @@ +package com.jverbruggen.jrides.models.ride.coaster; + +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.ride.AbstractRide; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class SimpleCoaster extends AbstractRide implements Coaster { + private List trains; + + public SimpleCoaster(String identifier, String displayName, List displayDescription, ItemStack displayItem, PlayerLocation warpLocation, boolean canExitDuringRide) { + super(identifier, displayName, displayDescription, displayItem, warpLocation, canExitDuringRide); + this.trains = new ArrayList<>(); + } + + @Override + public List getTrains() { + return trains; + } + + @Override + public void addTrain(Train train) { + trains.add(train); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/coaster/track/CircularSplineBasedTrack.java b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/track/CircularSplineBasedTrack.java new file mode 100644 index 00000000..6261b22d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/track/CircularSplineBasedTrack.java @@ -0,0 +1,123 @@ +package com.jverbruggen.jrides.models.ride.coaster.track; + +import com.jverbruggen.jrides.animator.coaster.NoLimitsExportPositionRecord; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.section.Section; + +import java.util.List; +import java.util.stream.Collectors; + +public class CircularSplineBasedTrack implements Track { + private final String identifier; + private List splinePositions; + private List
    sections; + private int splinePositionsCount; + + public CircularSplineBasedTrack(String identifier, List splinePositions, List
    sections) { + this.identifier = identifier; + this.splinePositions = splinePositions; + this.sections = sections; + this.splinePositionsCount = splinePositions.size(); + + this.sections.forEach(s-> s.setParentTrack(this)); + } + + @Override + public String getIdentifier() { + return identifier; + } + + @Override + public int getLength() { + return splinePositionsCount; + } + + @Override + public List
    getSections() { + return sections; + } + + @Override + public Section getNextSpawnSection() { + for(Section section : sections){ + if(!section.isOccupied() && section.canTrainSpawnOn()) return section; + } + return null; + } + + @Override + public Vector3 getLocationFor(Frame frame) { + if(!frame.getTrack().equals(this)) + throw new RuntimeException("Cannot get frame location if the frame is not on this track"); + + return splinePositions.get(frame.getValue()).toVector3(); + } + + @Override + public Quaternion getOrientationFor(Frame frame) { + if(!frame.getTrack().equals(this)) + throw new RuntimeException("Cannot get frame location if the frame is not on this track"); + + return splinePositions.get(frame.getValue()).getOrientation(); + } + + @Override + public List getAllPositions() { + return splinePositions.stream().map(NoLimitsExportPositionRecord::toVector3).collect(Collectors.toList()); + } +// +// @Override +// public Frame getFrameFor(int value) { +// return new CyclicFrame(value, this.getLength(), this); +// } + + @Override + public int getLowerFrame() { + return 0; + } + + @Override + public int getUpperFrame() { + return splinePositions.size()-1; + } + + @Override + public boolean inThisTrack(int frame) { + return getLowerFrame() <= frame && frame <= getUpperFrame(); + } + + @Override + public Track getNextTrack() { + return this; + } + + @Override + public Track getPreviousTrack() { + return this; + } + + @Override + public void setNextTrack(Track track) { + + } + + @Override + public void setPreviousTrack(Track track) { + + } + + public int countPositions(){ + return splinePositions.size(); + } + + public NoLimitsExportPositionRecord getPosition(int index){ + return splinePositions.get(index); + } + + @Override + public String toString() { + return ""; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/coaster/track/Track.java b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/track/Track.java new file mode 100644 index 00000000..d2c17762 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/track/Track.java @@ -0,0 +1,28 @@ +package com.jverbruggen.jrides.models.ride.coaster.track; + +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.section.Section; + +import java.util.List; + +public interface Track { + String getIdentifier(); + int getLength(); + + List
    getSections(); + Section getNextSpawnSection(); + + Vector3 getLocationFor(Frame frame); + Quaternion getOrientationFor(Frame frame); + List getAllPositions(); + int getLowerFrame(); + int getUpperFrame(); + boolean inThisTrack(int frame); + + Track getNextTrack(); + Track getPreviousTrack(); + void setNextTrack(Track track); + void setPreviousTrack(Track track); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/coaster/track/compound/CompoundTrack.java b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/track/compound/CompoundTrack.java new file mode 100644 index 00000000..4803bbe9 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/track/compound/CompoundTrack.java @@ -0,0 +1,115 @@ +package com.jverbruggen.jrides.models.ride.coaster.track.compound; + +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.section.Section; + +import java.util.ArrayList; +import java.util.List; + +public class CompoundTrack implements Track { + private final List children; + private final List
    sections; + private final List allPositions; + + public CompoundTrack(List children) { + this.children = children; + this.sections = new ArrayList<>(); + this.allPositions = new ArrayList<>(); + + this.children.forEach(s -> { + this.sections.addAll(s.getSections()); + this.allPositions.addAll(s.getAllPositions()); + }); + } + + public List getChildren() { + return children; + } + + @Override + public String toString() { + return ""; + } + + @Override + public String getIdentifier() { + return "Main Compound Track"; + } + + @Override + public int getLength() { + throw new RuntimeException("Not supported"); + } + + @Override + public List
    getSections() { + return sections; + } + + @Override + public Section getNextSpawnSection() { + for(Section section : sections){ + if(!section.isOccupied() && section.canTrainSpawnOn()) return section; + } + return null; + } + + @Override + public Vector3 getLocationFor(Frame frame) { + Track track = frame.getTrack(); + if(track.equals(this)) + throw new RuntimeException("Frame cannot be bound to compound track"); + return track.getLocationFor(frame); + } + + @Override + public Quaternion getOrientationFor(Frame frame) { + Track track = frame.getTrack(); + if(track.equals(this)) + throw new RuntimeException("Frame cannot be bound to compound track"); + return track.getOrientationFor(frame); + } + + @Override + public List getAllPositions() { + return allPositions; + } + + @Override + public int getLowerFrame() { + throw new RuntimeException("Cannot get frame bounds for compound track"); + } + + @Override + public int getUpperFrame() { + throw new RuntimeException("Cannot get frame bounds for compound track"); + } + + @Override + public boolean inThisTrack(int frame) { + return true; + } + + @Override + public Track getNextTrack() { + throw new RuntimeException("Cannot get adjacent track for compound track"); + } + + @Override + public Track getPreviousTrack() { + throw new RuntimeException("Cannot get adjacent track for compound track"); + } + + @Override + public void setNextTrack(Track track) { + throw new RuntimeException("Cannot set adjacent track for compound track"); + } + + @Override + public void setPreviousTrack(Track track) { + throw new RuntimeException("Cannot set adjacent track for compound track"); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/coaster/track/compound/CompoundTrackPart.java b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/track/compound/CompoundTrackPart.java new file mode 100644 index 00000000..559576f8 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/track/compound/CompoundTrackPart.java @@ -0,0 +1,9 @@ +package com.jverbruggen.jrides.models.ride.coaster.track.compound; + +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; + +public interface CompoundTrackPart extends Track { + Frame getStartFrame(); + Frame getEndFrame(); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/coaster/track/compound/LooseEndedSplineBasedTrack.java b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/track/compound/LooseEndedSplineBasedTrack.java new file mode 100644 index 00000000..f0967568 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/track/compound/LooseEndedSplineBasedTrack.java @@ -0,0 +1,151 @@ +package com.jverbruggen.jrides.models.ride.coaster.track.compound; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.coaster.NoLimitsExportPositionRecord; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.section.Section; + +import java.util.List; +import java.util.stream.Collectors; + +public class LooseEndedSplineBasedTrack implements CompoundTrackPart { + private final String identifier; + + private List splinePositions; + private List
    sections; + private int splinePositionsCount; + + private Track nextTrack; + private Track previousTrack; + + private Frame startFrame; + private Frame endFrame; + + public LooseEndedSplineBasedTrack(String identifier, List splinePositions, List
    sections, Frame startFrame, Frame endFrame) { + this.identifier = identifier; + this.splinePositions = splinePositions; + this.sections = sections; + this.splinePositionsCount = splinePositions.size(); + this.startFrame = startFrame; + this.endFrame = endFrame; + + this.startFrame.setTrack(this); + this.endFrame.setTrack(this); + + this.sections.forEach(s-> s.setParentTrack(this)); + } + + @Override + public String getIdentifier() { + return identifier; + } + + @Override + public int getLength() { + return splinePositionsCount; + } + + @Override + public List
    getSections() { + return sections; + } + + @Override + public Section getNextSpawnSection() { + for(Section section : sections){ + if(!section.isOccupied() && section.canTrainSpawnOn()) return section; + } + return null; + } + + @Override + public Vector3 getLocationFor(Frame frame) { + if(!frame.getTrack().equals(this)) + throwTrackNotSameException(frame); + + if(frame.getValue() >= splinePositions.size()) + JRidesPlugin.getLogger().severe(frame + " out of bounds"); + + return splinePositions.get(frame.getValue()).toVector3(); + } + + @Override + public Quaternion getOrientationFor(Frame frame) { + if(!frame.getTrack().equals(this)) + throwTrackNotSameException(frame); + + return splinePositions.get(frame.getValue()).getOrientation(); + } + + @Override + public List getAllPositions() { + return splinePositions.stream().map(NoLimitsExportPositionRecord::toVector3).collect(Collectors.toList()); + } + + @Override + public int getLowerFrame() { + return startFrame.getValue(); + } + + @Override + public int getUpperFrame() { + return endFrame.getValue(); + } + + @Override + public boolean inThisTrack(int frame) { + return this.startFrame.getValue() <= frame && frame <= this.endFrame.getValue(); + } + + public int countPositions(){ + return splinePositions.size(); + } + + public NoLimitsExportPositionRecord getPosition(int index){ + return splinePositions.get(index); + } + + @Override + public String toString() { + return ""; + } + + @Override + public Track getNextTrack() { + return nextTrack; + } + + @Override + public Track getPreviousTrack() { + return previousTrack; + } + + @Override + public void setNextTrack(Track track) { + nextTrack = track; + } + + @Override + public void setPreviousTrack(Track track) { + previousTrack = track; + } + + @Override + public Frame getStartFrame() { + return startFrame; + } + + @Override + public Frame getEndFrame() { + return endFrame; + } + + private void throwTrackNotSameException(Frame frame){ + throw new RuntimeException("Cannot get frame location if the frame is not on this track.\n" + + "This: " + this + ", other: " + frame.getTrack() + "\n" + + "Frame: " + frame); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/coaster/trackswitch/SwitchPosition.java b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/trackswitch/SwitchPosition.java new file mode 100644 index 00000000..77a43dbd --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/trackswitch/SwitchPosition.java @@ -0,0 +1,48 @@ +package com.jverbruggen.jrides.models.ride.coaster.trackswitch; + +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.Section; +import com.jverbruggen.jrides.models.ride.section.reference.SectionReference; + +import javax.annotation.Nullable; +import java.util.Map; + +public class SwitchPosition { + private String destinationReference; + private Section destination; + + public SwitchPosition(String destinationReference) { + this.destinationReference = destinationReference; + this.destination = null; + } + + public String getDestinationReference() { + return destinationReference; + } + + public Section getDestination() { + return destination; + } + + public void setDestination(Section destination) { + this.destination = destination; + } + + public void populateWith(Map sectionMap){ + Section found = sectionMap.entrySet().stream() + .filter(entry -> entry.getKey().getSectionIdentifier().equalsIgnoreCase(destinationReference)) + .findFirst().orElseThrow().getValue(); + setDestination(found); + } + + public boolean availableFor(@Nullable Train train){ + Train occupiedBy = destination.getOccupiedBy(); + Train reservedBy = destination.getReservedBy(); + return (occupiedBy == null || occupiedBy == train) && (reservedBy == null || reservedBy == train); + } + + @Override + public String toString() { + return ""; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/AbstractVehicle.java b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/AbstractVehicle.java new file mode 100644 index 00000000..992fcb72 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/AbstractVehicle.java @@ -0,0 +1,69 @@ +package com.jverbruggen.jrides.models.ride.coaster.train; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.models.entity.Player; +import org.bukkit.SoundCategory; + +import java.util.ArrayList; +import java.util.List; + +public abstract class AbstractVehicle implements Vehicle { + private final String name; + private List passengers; + private boolean crashed; + private boolean debugMode; + + public AbstractVehicle(String name, boolean debugMode) { + this.name = name; + this.crashed = false; + this.passengers = new ArrayList<>(); + this.debugMode = debugMode; + } + + @Override + public String getName() { + return name; + } + + @Override + public void setCrashed(boolean crashed) { + this.crashed = crashed; + } + + @Override + public boolean isCrashed() { + return crashed; + } + + @Override + public List getPassengers() { + return passengers; + } + + public void removePassenger(Player player){ + passengers.remove(player); + } + + public void addPassenger(Player player){ + passengers.add(player); + } + + @Override + public void onPlayerEnter(Player player) { + addPassenger(player); + } + + @Override + public void onPlayerExit(Player player) { + removePassenger(player); + } + + public boolean isDebugMode() { + return debugMode; + } + + protected void playSound(String soundName){ + if(soundName == null) return; + JRidesPlugin.getWorld().playSound(getCurrentLocation().toBukkitLocation(JRidesPlugin.getWorld()), soundName, SoundCategory.MASTER, 0.1f, 1f); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/CoasterCart.java b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/CoasterCart.java new file mode 100644 index 00000000..ccc8e489 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/CoasterCart.java @@ -0,0 +1,60 @@ +package com.jverbruggen.jrides.models.ride.coaster.train; + +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.CartMovement; +import com.jverbruggen.jrides.effect.handle.train.TrainEffectTriggerHandle; +import com.jverbruggen.jrides.models.math.Matrix4x4; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.math.VectorQuaternionState; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.seat.SeatHost; + + +public interface CoasterCart extends SeatHost { + static VectorQuaternionState calculateLocation(Vector3 trackLocation, Vector3 cartOffset, Quaternion orientation, Quaternion cartRotationOffset){ + Matrix4x4 matrix = new Matrix4x4(); + matrix.rotate(orientation); + matrix.translate(cartOffset); + matrix.rotate(cartRotationOffset); + Vector3 cartTrackOffsetVector = matrix.toVector3(); + Vector3 totalVector = Vector3.add(trackLocation, cartTrackOffsetVector); + + final Vector3 armorstandHeightCompensationVector = getArmorstandHeightCompensationVector(); + totalVector = Vector3.add(totalVector, armorstandHeightCompensationVector); + + return new VectorQuaternionState(totalVector, matrix.getRotation()); + } + + static Vector3 getArmorstandHeightCompensationVector(){ + return new Vector3(0, -1.8, 0); + } + + String getName(); + Frame getFrame(); + Vector3 getTrackOffset(); + Vector3 getPosition(); + + /** + * Total orientation of the cart (track rotation + rotation offset) + * @return + */ + Quaternion getOrientation(); + + /** + * Get individual rotation offset (usually a state of rotating the carts along the track) + * @return + */ + Quaternion getRotationOffset(); + void setPosition(Vector3 position, Quaternion orientation); + void setPosition(Vector3 position); + void setPosition(CartMovement cartMovement); + void setParentTrain(Train train); + Train getParentTrain(); + boolean shouldFaceForwards(); + void setInvertedFrameAddition(boolean inverted); + void updateCustomOrientationOffset(Vector3 orientationOffset); + + void setNextEffect(TrainEffectTriggerHandle nextEffect); + void playEffects(); + +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/CoasterSeat.java b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/CoasterSeat.java new file mode 100644 index 00000000..fd25a4fb --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/CoasterSeat.java @@ -0,0 +1,40 @@ +package com.jverbruggen.jrides.models.ride.coaster.train; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.entity.armorstand.VirtualArmorstand; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.math.Vector3PlusYaw; +import com.jverbruggen.jrides.models.ride.seat.AbstractSeat; +import com.jverbruggen.jrides.models.ride.seat.SeatHost; + +public class CoasterSeat extends AbstractSeat { + private CoasterCart parentCart; + + public CoasterSeat(RideHandle parentRideHandle, VirtualEntity virtualEntity, Vector3PlusYaw offset) { + super(parentRideHandle, null, virtualEntity, offset); + this.parentCart = null; + } + + @Override + public void setParentSeatHost(SeatHost seatHost) { + super.setParentSeatHost(seatHost); + + if(seatHost instanceof CoasterCart) + parentCart = (CoasterCart) seatHost; + else throw new RuntimeException("Cannot set non-coaster-cart as parent for coaster seat"); + } + + @Override + public SeatHost getParentSeatHost() { + return parentCart; + } + + public CoasterCart getParentCart() { + return this.parentCart; + } + + public static Vector3 getHeightCompensation(){ + return new Vector3(0, 1.5, 0); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/SimpleCoasterCart.java b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/SimpleCoasterCart.java new file mode 100644 index 00000000..ab50c924 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/SimpleCoasterCart.java @@ -0,0 +1,237 @@ +package com.jverbruggen.jrides.models.ride.coaster.train; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.CartMovement; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.effect.handle.train.TrainEffectTriggerHandle; +import com.jverbruggen.jrides.event.player.PlayerSitDownEvent; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.ride.seat.Seat; +import com.jverbruggen.jrides.models.ride.factory.SeatFactory; +import org.bukkit.ChatColor; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class SimpleCoasterCart implements CoasterCart { + private final String name; + private final List seats; + private final VirtualEntity modelEntity; + private final Vector3 trackOffset; + private final Quaternion trackRotationOffset; + private final Frame frame; + private Train parentTrain; + + private boolean hasEffects; + private TrainEffectTriggerHandle nextEffect; + + private Quaternion currentOrientation; + private Vector3 orientationOffset; + + public SimpleCoasterCart(String name, List seats, VirtualEntity modelEntity, Vector3 trackOffset, Quaternion trackRotationOffset, Frame frame) { + this.name = name; + this.seats = seats; + this.modelEntity = modelEntity; + this.trackOffset = trackOffset; + this.trackRotationOffset = trackRotationOffset; + this.frame = frame; + this.parentTrain = null; + this.currentOrientation = new Quaternion(0,0,0,0); + this.orientationOffset = null; + + this.nextEffect = null; + this.hasEffects = false; + + seats.forEach(s -> s.setParentSeatHost(this)); + } + + @Override + public String getName() { + return name; + } + + @Override + public List getSeats() { + return new ArrayList<>(seats); + } + + public List getCoasterSeats(){ + return seats; + } + + @Override + public List getPassengers() { + return seats.stream() + .filter(Seat::hasPassenger) + .map(Seat::getPassenger) + .collect(Collectors.toList()); + } + + @Override + public Frame getFrame() { + return frame; + } + + @Override + public Vector3 getTrackOffset() { + return trackOffset; + } + + @Override + public Vector3 getPosition() { + return modelEntity.getLocation(); + } + + /** + * Get total orientation that is used in display + * @return + */ + @Override + public Quaternion getOrientation() { + return currentOrientation; + } + + @Override + public Quaternion getRotationOffset() { + return trackRotationOffset; + } + + @Override + public void updateCustomOrientationOffset(Vector3 orientationOffset){ + this.orientationOffset = orientationOffset; + updateOrientation(calculateOrientationWithOffset(currentOrientation)); + } + + private Quaternion calculateOrientationWithOffset(Quaternion original){ + Quaternion orientationWithOffset = original.clone(); + if(this.orientationOffset != null) + orientationWithOffset.rotateYawPitchRoll(this.orientationOffset); + + return orientationWithOffset; + } + + private void updateOrientation(Quaternion orientation){ + currentOrientation = orientation; + modelEntity.setRotation(currentOrientation); + } + + @Override + public void setPosition(Vector3 position, Quaternion orientation) { + updateOrientation(calculateOrientationWithOffset(orientation)); + setPosition(position); + } + + @Override + public void setPosition(Vector3 position) { + modelEntity.setLocation(position); + SeatFactory.moveCoasterSeats(seats, position, currentOrientation); + } + + @Override + public void setPosition(CartMovement cartMovement) { + setPosition(cartMovement.getLocation(), cartMovement.getOrientation()); + } + + @Override + public void setRestraint(boolean locked) { + for(Seat seat : getCoasterSeats()){ + seat.setRestraint(locked); + } + } + + @Override + public boolean getRestraintState() { + return getCoasterSeats().stream().allMatch(Seat::restraintsActive); + } + + @Override + public PlayerLocation getEjectLocation() { + return getParentTrain().getHandle().getCoasterHandle().getEjectLocation(); + } + + @Override + public RideHandle getRideHandle() { + return getParentTrain().getHandle().getCoasterHandle(); + } + + @Override + public void onPlayerEnter(Player player) { + getParentTrain().onPlayerEnter(player); + PlayerSitDownEvent.send(player, getParentTrain().getHandle().getCoasterHandle().getRide()); + + // Potentially rider wants to inspect frames + org.bukkit.entity.Player bukkitPlayer = player.getBukkitPlayer(); + ItemStack itemInHand = bukkitPlayer.getInventory().getItemInMainHand(); + if(bukkitPlayer.hasPermission(Permissions.ELEVATED_STATUS_INSPECTION) + && itemInHand.getItemMeta() != null + && itemInHand.getItemMeta().getDisplayName().stripTrailing().equalsIgnoreCase("jrides:frame-inspect")){ + getParentTrain().addPositionMessageListener(player); + player.sendMessage(ChatColor.GRAY + "(debug) Now inspecting frames"); + } + } + + @Override + public void onPlayerExit(Player player) { + getParentTrain().onPlayerExit(player); + getParentTrain().removePositionMessageListener(player); + } + + @Override + public void setParentTrain(Train train) { + parentTrain = train; + } + + @Override + public Train getParentTrain() { + return parentTrain; + } + + @Override + public void ejectPassengers() { + seats.forEach(s -> { + Player passenger = s.getPassenger(); + if(passenger != null){ + s.setPassenger(null); + PlayerLocation ejectLocation = (parentTrain.isStationary()) + ? parentTrain.getStationaryAt().getEjectLocation() + : getParentTrain().getHandle().getCoasterHandle().getEjectLocation(); + if(ejectLocation != null) + passenger.teleport(ejectLocation, true); + } + }); + } + + @Override + public boolean shouldFaceForwards() { + return !frame.isInvertedFrameAddition(); + } + + @Override + public void setInvertedFrameAddition(boolean inverted) { + frame.setInvertedFrameAddition(inverted); + } + + + @Override + public void setNextEffect(TrainEffectTriggerHandle nextEffect) { + this.nextEffect = nextEffect; + this.hasEffects = true; + } + + @Override + public void playEffects() { + + } + + @Override + public void despawn() { + modelEntity.despawn(); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/SimpleTrain.java b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/SimpleTrain.java new file mode 100644 index 00000000..11500707 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/SimpleTrain.java @@ -0,0 +1,372 @@ +package com.jverbruggen.jrides.models.ride.coaster.train; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.models.entity.MessageReceiver; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.TrackEnd; +import com.jverbruggen.jrides.models.properties.TrainEnd; +import com.jverbruggen.jrides.models.ride.CoasterStationHandle; +import com.jverbruggen.jrides.models.ride.section.Section; + +import java.util.ArrayList; +import java.util.List; + +public class SimpleTrain extends AbstractVehicle implements Train { + private final List carts; + private final Frame middleOfTrainFrame; + private final Frame headOfTrainFrame; + private final Frame tailOfTrainFrame; + private final List
    currentSections; + private final List
    reservedSections; + private Vector3 headLocation; + private Vector3 middleLocation; + private Vector3 tailLocation; + + private CoasterStationHandle onStation; + private TrainHandle trainHandle; + + private String statusMessage; + private final List statusMessageListeners; + private final List positionMessageListeners; + private boolean drivingTowardsPositiveDirection; + private boolean forwards; + + public SimpleTrain(String name, List carts, Frame headOfTrainFrame, Frame middleOfTrainFrame, Frame tailOfTrainFrame, + Vector3 headLocation, Vector3 middleLocation, Vector3 tailLocation, Section section, boolean debugMode) { + super(name, debugMode); + this.carts = carts; + this.headOfTrainFrame = headOfTrainFrame; + this.middleOfTrainFrame = middleOfTrainFrame; + this.tailOfTrainFrame = tailOfTrainFrame; + + this.currentSections = new ArrayList<>(); + this.currentSections.add(section); + this.headLocation = headLocation; + this.middleLocation = middleLocation; + this.tailLocation = tailLocation; + + this.reservedSections = new ArrayList<>(); + + this.onStation = null; + this.trainHandle = null; + this.statusMessage = ""; + this.statusMessageListeners = new ArrayList<>(); + this.positionMessageListeners = new ArrayList<>(); + + this.drivingTowardsPositiveDirection = true; + this.forwards = true; + + getCarts().forEach(c -> c.setParentTrain(this)); + } + + @Override + public List getCarts() { + return carts; + } + + @Override + public int size() { + return carts.size(); + } + + @Override + public Frame getFrontFacingTrainFrame() { + return forwards ? getHeadOfTrainFrame() : getTailOfTrainFrame(); + } + + @Override + public Frame getBackFacingTrainFrame() { + return forwards ? getTailOfTrainFrame() : getHeadOfTrainFrame(); + } + + @Override + public Frame getMiddleOfTrainFrame() { + return middleOfTrainFrame; + } + + @Override + public Frame getHeadOfTrainFrame() { + return headOfTrainFrame; + } + + @Override + public Frame getTailOfTrainFrame() { + return tailOfTrainFrame; + } + + @Override + public Vector3 getCurrentHeadLocation() { + return headLocation; + } + + @Override + public Vector3 getCurrentLocation() { + return middleLocation; + } + + @Override + public Vector3 getCurrentTailLocation() { + return tailLocation; + } + + @Override + public void setCurrentLocation(Vector3 headLocation, Vector3 middleLocation, Vector3 tailLocation) { + this.headLocation = headLocation; + this.middleLocation = middleLocation; + this.tailLocation = tailLocation; + } + + @Override + public Vector3 getMassMiddlePoint() { + return Train.calculateMassMiddlePoint(headLocation, middleLocation, tailLocation); + } + + @Override + public List
    getReservedSections() { + return reservedSections; + } + + @Override + public void addReservedSection(Section section) { + reservedSections.add(section); + } + + @Override + public void removeReservedSection(Section section) { + reservedSections.remove(section); + } + + @Override + public List
    getCurrentSections() { + return currentSections; + } + + @Override + public Section getNextSection() { + return getHeadSection().next(this, false); + } + + @Override + public Section getHeadSection() { + if(currentSections.size() == 0) throw new RuntimeException("Train occupies 0 sections"); + return currentSections.get(0); + } + + @Override + public Section getTailSection() { + if(currentSections.size() == 0) throw new RuntimeException("Train occupies 0 sections"); + return currentSections.get(currentSections.size()-1); + } + + @Override + public void addCurrentSection(Section section) { + addCurrentSection(section, TrainEnd.HEAD); + } + + @Override + public void addCurrentSection(Section section, TrainEnd trainEnd) { + if(trainEnd.equals(TrainEnd.HEAD)){ + currentSections.add(0, section); + } + else + currentSections.add(section); + } + + @Override + public void removeCurrentSection(Section section) { + if(!this.currentSections.contains(section)) throw new RuntimeException("Section removal mismatch"); + this.currentSections.remove(section); + } + + @Override + public void setRestraintForAll(boolean locked) { + for(CoasterCart cart : getCarts()){ + cart.setRestraint(locked); + } + + if(locked) playRestraintCloseSound(); + else playRestraintOpenSound(); + } + + @Override + public boolean getRestraintState() { + return carts.stream().allMatch(CoasterCart::getRestraintState); + } + + @Override + public boolean equals(Train other) { + return this.getName().equalsIgnoreCase(other.getName()); + } + + @Override + public TrackEnd getDirection() { + return getHandle().getSpeed().isPositive() ? TrackEnd.END : TrackEnd.START; + } + + @Override + public boolean isPositiveDrivingDirection() { + return drivingTowardsPositiveDirection; + } + + @Override + public boolean drivingTowardsEnd() { + return getDirection() == TrackEnd.END; + } + + @Override + public boolean isFacingForwards() { + return forwards; + } + + @Override + public void setFacingForwards(boolean forwards) { + this.forwards = forwards; + } + + @Override + public void setDrivingDirection(boolean positive) { + drivingTowardsPositiveDirection = positive; + getHandle().getSpeed().setInverted(!forwards); // TODO: untested + } + + @Override + public void setInvertedFrameAddition(boolean inverted) { + headOfTrainFrame.setInvertedFrameAddition(inverted); + middleOfTrainFrame.setInvertedFrameAddition(inverted); + tailOfTrainFrame.setInvertedFrameAddition(inverted); + + for(CoasterCart cart : getCarts()){ + cart.setInvertedFrameAddition(inverted); + } + } + + @Override + public void onPlayerEnter(Player player) { + addPassenger(player); + if(statusModeEnabled(player)){ + addStatusMessageListener(player); + } + + if(isStationary()){ + onStation.onPlayerEnter(player); + } + } + + @Override + public void onPlayerExit(Player player) { + removePassenger(player); + removeStatusMessageListener(player); + } + + + @Override + public void setStationaryAt(CoasterStationHandle stationaryAt) { + this.onStation = stationaryAt; + } + + @Override + public boolean isStationary() { + return onStation != null; + } + + @Override + public CoasterStationHandle getStationaryAt() { + return onStation; + } + + @Override + public void setHandle(TrainHandle trainHandle) { + this.trainHandle = trainHandle; + } + + @Override + public TrainHandle getHandle() { + return trainHandle; + } + + @Override + public void ejectPassengers() { + carts.forEach(CoasterCart::ejectPassengers); + } + + @Override + public void playRestraintOpenSound() { + playSound(trainHandle.getCoasterHandle().getSounds().getRestraintOpen()); + } + + @Override + public void playRestraintCloseSound() { + playSound(trainHandle.getCoasterHandle().getSounds().getRestraintClose()); + } + + @Override + public void playDispatchSound() { + playSound(trainHandle.getCoasterHandle().getSounds().getDispatch()); + } + + @Override + public void sendPositionMessage(String positionMessage) { + if(positionMessageListeners == null || positionMessageListeners.size() == 0) return; + positionMessageListeners.forEach(r->r.sendMessage(positionMessage)); + } + + @Override + public void addPositionMessageListener(MessageReceiver messageReceiver) { + positionMessageListeners.add(messageReceiver); + } + + @Override + public void removePositionMessageListener(MessageReceiver messageReceiver) { + positionMessageListeners.remove(messageReceiver); + } + + @Override + public boolean positionMessageEnabled(MessageReceiver messageReceiver) { + return positionMessageListeners.contains(messageReceiver); + } + + @Override + public void setStatusMessage(String statusMessage) { + if(!isDebugMode()) return; + this.statusMessage = statusMessage; + if(!statusMessage.equals("")) + statusMessageListeners.forEach(l -> l.sendMessage(statusMessage)); + } + + @Override + public void addStatusMessageListener(Player player) { + if(!isDebugMode()) return; + statusMessageListeners.add(player); + player.sendMessage(statusMessage); + } + + @Override + public void removeStatusMessageListener(Player player) { + if(!isDebugMode()) return; + statusMessageListeners.remove(player); + } + + @Override + public boolean statusModeEnabled(Player player) { + return isDebugMode() && player.getBukkitPlayer().hasPermission(Permissions.ELEVATED_STATUS_INSPECTION); + } + + @Override + public void despawn() { + carts.forEach(CoasterCart::despawn); + } + + @Override + public void reset() { + getHandle().resetEffects(); + } + + @Override + public String toString() { + String forwards_indicator = forwards ? "F" : "B"; + return ""; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/Train.java b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/Train.java new file mode 100644 index 00000000..dc43c960 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/Train.java @@ -0,0 +1,81 @@ +package com.jverbruggen.jrides.models.ride.coaster.train; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.models.entity.MessageReceiver; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.TrackEnd; +import com.jverbruggen.jrides.models.properties.TrainEnd; +import com.jverbruggen.jrides.models.ride.CoasterStationHandle; +import com.jverbruggen.jrides.models.ride.section.Section; + +import java.util.List; + +public interface Train extends Vehicle { + String getName(); + List getCarts(); + int size(); + + Frame getFrontFacingTrainFrame(); + Frame getBackFacingTrainFrame(); + + Frame getMiddleOfTrainFrame(); + Frame getHeadOfTrainFrame(); + Frame getTailOfTrainFrame(); + Vector3 getCurrentHeadLocation(); + Vector3 getCurrentLocation(); + Vector3 getCurrentTailLocation(); + void setCurrentLocation(Vector3 headLocation, Vector3 middleLocation, Vector3 tailLocation); + Vector3 getMassMiddlePoint(); + + List
    getReservedSections(); + void addReservedSection(Section section); + void removeReservedSection(Section section); + + List
    getCurrentSections(); + Section getNextSection(); + Section getHeadSection(); + Section getTailSection(); + void addCurrentSection(Section section); + void addCurrentSection(Section section, TrainEnd sectionEnd); + void removeCurrentSection(Section section); + + void setRestraintForAll(boolean locked); + boolean getRestraintState(); + + void setCrashed(boolean crashed); + boolean isCrashed(); + boolean equals(Train other); + TrackEnd getDirection(); + boolean isPositiveDrivingDirection(); + boolean drivingTowardsEnd(); + boolean isFacingForwards(); + void setFacingForwards(boolean forwards); + void setDrivingDirection(boolean positive); + void setInvertedFrameAddition(boolean inverted); + + void setStationaryAt(CoasterStationHandle stationaryAt); + + CoasterStationHandle getStationaryAt(); + + void setHandle(TrainHandle trainHandle); + TrainHandle getHandle(); + + static Vector3 calculateMassMiddlePoint(Vector3 headLocation, Vector3 middleLocation, Vector3 tailLocation){ + return Vector3.average(headLocation, middleLocation, middleLocation, tailLocation); // Middle is twice as heavy as sides + } + + void sendPositionMessage(String positionMessage); + void addPositionMessageListener(MessageReceiver messageReceiver); + void removePositionMessageListener(MessageReceiver messageReceiver); + boolean positionMessageEnabled(MessageReceiver messageReceiver); + + void setStatusMessage(String statusMessage); + void addStatusMessageListener(Player player); + void removeStatusMessageListener(Player player); + boolean statusModeEnabled(Player player); + + void despawn(); + void reset(); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/Vehicle.java b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/Vehicle.java new file mode 100644 index 00000000..67a40da0 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/train/Vehicle.java @@ -0,0 +1,34 @@ +package com.jverbruggen.jrides.models.ride.coaster.train; + +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.math.Vector3; + +import java.util.List; + +public interface Vehicle { + List getPassengers(); + void onPlayerEnter(Player player); + void onPlayerExit(Player player); + + boolean isStationary(); + + /** + * @return true if restraints are closed + */ + boolean getRestraintState(); + void setRestraintForAll(boolean closed); + + void ejectPassengers(); + + void playRestraintOpenSound(); + + void playRestraintCloseSound(); + + void playDispatchSound(); + + String getName(); + + void setCrashed(boolean crashed); + boolean isCrashed(); + Vector3 getCurrentLocation(); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/coaster/transfer/Transfer.java b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/transfer/Transfer.java new file mode 100644 index 00000000..05c87737 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/transfer/Transfer.java @@ -0,0 +1,335 @@ +package com.jverbruggen.jrides.models.ride.coaster.transfer; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.*; +import com.jverbruggen.jrides.models.ride.coaster.train.CoasterCart; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.Section; +import com.jverbruggen.jrides.models.ride.section.Unlockable; +import com.jverbruggen.jrides.models.ride.section.reference.SectionReference; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class Transfer implements Unlockable { + private final Vector3 origin; + + private TrainHandle train; + private Vector3 currentLocation; + private Quaternion currentOrientation; + private Matrix4x4 currentRotationMatrix; + + private boolean requestPending; + private boolean moving; + private boolean locked; + private final List cartPositions; + + private final List possiblePositions; + private TransferPosition targetPosition; + private Vector3 fromLocation; + private Quaternion fromOrientation; + + private int animationTicks; + private int animationFrameState; + + private Vector3 bakedOffsetLocation; + private Quaternion bakedOffsetOrientation; + + private final VirtualEntity modelEntity; + private final Vector3 modelOffset; + private final Vector3 modelOffsetRotation; + + public Transfer(List possiblePositions, VirtualEntity modelEntity, Vector3 origin, Vector3 modelOffset, Vector3 modelOffsetRotation) { + this.origin = origin; + this.locked = false; + this.moving = false; + this.requestPending = false; + this.cartPositions = new ArrayList<>(); + this.possiblePositions = possiblePositions; + + TransferPosition firstTransferposition = possiblePositions.get(0); + this.currentLocation = firstTransferposition.getLocation(); + this.currentOrientation = firstTransferposition.getOrientation(); + this.currentRotationMatrix = calculateRotationMatrix(currentLocation, currentOrientation); + + this.fromLocation = null; + this.fromOrientation = null; + this.targetPosition = firstTransferposition; + this.animationTicks = 0; + this.animationFrameState = 0; + + calculateBakedOffset(); + + this.modelEntity = modelEntity; + this.modelOffset = modelOffset; + this.modelOffsetRotation = modelOffsetRotation; + + updateModelPosition(); + } + + public void lockTrain(){ + if(!hasTrain()) throw new RuntimeException("Cannot lock train on transfer if no train is present"); + this.locked = true; + + Matrix4x4 rotationMatrix = new Matrix4x4(); + rotationMatrix.translate(currentLocation); + rotationMatrix.rotate(currentOrientation); + + for(CoasterCart cart : train.getTrain().getCarts()){ + Quaternion currentCartOrientation = cart.getOrientation(); + if(currentCartOrientation == null) throw new RuntimeException("Cart doesn't have orientation"); + + Vector3 nonRotatedCartPosition = cart.getPosition(); + nonRotatedCartPosition = Vector3.add(nonRotatedCartPosition, Vector3.subtract(currentLocation, getOrigin())); + + Vector3 offsetCartPosition = Vector3.subtract(nonRotatedCartPosition, currentLocation); + + Quaternion orientationOffset = Quaternion.divide(currentCartOrientation, currentOrientation); + cartPositions.add(new CartOffsetFromTransferOrigin(offsetCartPosition, orientationOffset, cart)); + } + } + + public void unlockTrain(){ + if(!hasTrain()) throw new RuntimeException("Cannot unlock train on transfer if no train is present"); + this.locked = false; + this.calculateBakedOffset(); + this.cartPositions.clear(); + } + + public void setTrain(TrainHandle train){ + if(this.locked) + throw new RuntimeException("Cannot set train if transfer is locked"); + + if(this.train != null && train != null && this.train != train) + throw new RuntimeException("Cannot have multiple trains on same transfer"); + + this.train = train; + } + + private boolean hasTrain(){ + return train != null; + } + + public TrainHandle getTrain(){ + return train; + } + + public boolean tick(){ + if(moving){ + return doMoveTick(); + } + return false; + } + + private boolean doMoveTick(){ + if(animationFrameState >= animationTicks){ + move(targetPosition.getLocation().clone(), targetPosition.getOrientation().clone()); + + animationFrameState = 0; + moving = false; + this.calculateBakedOffset(); + return true; + }else{ + // -- Calculate new transfer position + double theta = (double)animationFrameState / (double)animationTicks; + if(theta > 1) theta = 1d; + Vector3 delta = Vector3.subtract(targetPosition.getLocation(), fromLocation); + + Vector3 increment = Vector3.multiply(delta, theta); + Vector3 newLocation = Vector3.add(fromLocation, increment); + Quaternion newOrientation = Quaternion.lerp(fromOrientation, targetPosition.getOrientation(), theta); + + move(newLocation, newOrientation); + animationFrameState++; + return false; + } + } + + private void move(Vector3 newLocation, Quaternion newOrientation){ + if(!locked && hasTrain()) throw new RuntimeException("Cannot move transfer if train is not locked"); + + currentLocation = newLocation; + currentOrientation = newOrientation; + currentRotationMatrix = calculateRotationMatrix(newLocation, newOrientation); + updateModelPosition(); + + if(hasTrain()){ + moveTrain(); + } + } + + private void updateModelPosition(){ + Vector3 armorstandCompenstationVector = CoasterCart.getArmorstandHeightCompensationVector(); + Vector3 modelOffsetCompensated = Vector3.subtract(modelOffset, armorstandCompenstationVector); + + Matrix4x4 orientationMatrix = new Matrix4x4(); + orientationMatrix.translate(getCurrentLocation()); + orientationMatrix.translate(armorstandCompenstationVector); + orientationMatrix.rotate(getCurrentOrientation()); + orientationMatrix.translate(modelOffsetCompensated); + + Quaternion modelOrientation = orientationMatrix.getRotation(); + + Vector3 modelLocation = orientationMatrix.toVector3(); + + modelEntity.setLocation(modelLocation); + modelOrientation.rotateYawPitchRoll(modelOffsetRotation); + modelEntity.setRotation(modelOrientation); + } + + private void moveTrain(){ + Vector3 armorstandCompenstationVector = CoasterCart.getArmorstandHeightCompensationVector(); + + for(CartOffsetFromTransferOrigin cartProgramming : cartPositions){ + Matrix4x4 matrix = new Matrix4x4(); + matrix.translate(getCurrentLocation()); + + Quaternion cartOrientation = cartProgramming.orientation(); + Vector3 cartPosition = cartProgramming.position(); + + matrix.translate(armorstandCompenstationVector); + matrix.rotate(getCurrentOrientation()); + matrix.translate(Vector3.subtract(cartPosition, armorstandCompenstationVector)); + + Quaternion newCartOrientation = matrix.getRotation().clone(); + newCartOrientation.multiply(cartOrientation); + + cartProgramming.cart().setPosition(matrix.toVector3(), newCartOrientation); + } + } + + public Vector3 getCurrentLocation() { + return currentLocation; + } + + public Quaternion getCurrentOrientation(){ + return currentOrientation; + } + + public List getPossiblePositions() { + return possiblePositions; + } + + public void setTargetPosition(int i, boolean requestPending){ + if(this.requestPending) + throw new RuntimeException("Cannot change target position if another request is still pending"); + + TransferPosition newTargetPosition = possiblePositions.get(i); + if(targetPosition == newTargetPosition) + return; + + int fromTicks = 0; + if(targetPosition != null) + fromTicks = targetPosition.getMoveTicks(); + + fromLocation = currentLocation.clone(); + fromOrientation = currentOrientation.clone(); + targetPosition = newTargetPosition; + animationFrameState = 0; + animationTicks = Math.abs(targetPosition.getMoveTicks() - fromTicks); + moving = true; + + if(requestPending) + this.requestPending = true; + } + + public boolean hasReachedRequest(){ + return requestPending && !moving; + } + + public void releaseRequest(){ + if(!this.requestPending) + throw new RuntimeException("No request was pending when releasing"); + + this.requestPending = false; + } + + private void calculateBakedOffset(){ + TransferPosition origin = possiblePositions.get(0); + bakedOffsetLocation = Vector3.subtract(currentLocation, origin.getLocation()); + bakedOffsetOrientation = Quaternion.diff(origin.getOrientation(), currentOrientation); + } + + private Matrix4x4 calculateRotationMatrix(Vector3 location, Quaternion orientation){ + Matrix4x4 orientationMatrix = new Matrix4x4(); + orientationMatrix.translate(location); + orientationMatrix.rotate(orientation); + return orientationMatrix; + } + + public TransferPosition getCurrentTransferPosition(){ + return targetPosition; + } + + public void populateTransferPositionSections(Map sectionMap){ + for(TransferPosition position : possiblePositions){ + String sectionAtStartReference = position.getSectionAtStartReference(); + String sectionAtEndReference = position.getSectionAtEndReference(); + + Section sectionAtStart = null; + Section sectionAtEnd = null; + + if(sectionAtStartReference != null && !sectionAtStartReference.equals("")) + sectionAtStart = SectionReference.findByIdentifier(sectionAtStartReference, sectionMap); + + if(sectionAtEndReference != null && !sectionAtEndReference.equals("")) + sectionAtEnd = SectionReference.findByIdentifier(sectionAtEndReference, sectionMap); + + position.setSectionAtStart(sectionAtStart); + position.setSectionAtEnd(sectionAtEnd); + } + } + + public void trainExitedTransfer(){ + setTrain(null); + } + + public void resetPosition(){ + setTargetPosition(0, false); + } + + public Vector3 getOrigin(){ + return origin; + } + + public boolean isMoving(){ + return moving; + } + + public boolean canSafelyInteractWith(TrainHandle train){ + if(hasTrain()){ + return getTrain() == train; + } + if(isMoving()) + return false; + if(train == null) + return true; + + List
    currentTrainSections = train.getTrain().getCurrentSections(); + TransferPosition currentTransferPosition = getCurrentTransferPosition(); + + Section currentSectionAtStart = currentTransferPosition.getSectionAtStart(); + Section currentSectionAtEnd = currentTransferPosition.getSectionAtEnd(); + + if(currentSectionAtStart != null && currentTrainSections.contains(currentSectionAtStart)) + return true; + else if(currentSectionAtEnd != null && currentTrainSections.contains(currentSectionAtEnd)) + return true; + else + return false; + } + + @Override + public void unlock(Train authority) { + if(this.train != null && this.train != authority.getHandle()){ + throw new RuntimeException("Train " + authority.getName() + " tried to unlock transfer while it wasn't the occupier"); + } + trainExitedTransfer(); + resetPosition(); + } +} + +record CartOffsetFromTransferOrigin(Vector3 position, Quaternion orientation, CoasterCart cart) { +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/coaster/transfer/TransferPosition.java b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/transfer/TransferPosition.java new file mode 100644 index 00000000..18faaebc --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/coaster/transfer/TransferPosition.java @@ -0,0 +1,93 @@ +package com.jverbruggen.jrides.models.ride.coaster.transfer; + +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.ride.section.Section; + +public class TransferPosition { + private final Vector3 location; + private final Quaternion orientation; + private final int moveTicks; + + private final String sectionAtStartReference; + private final String sectionAtEndReference; + private final boolean sectionAtStartForwards; + private final boolean sectionAtEndForwards; + private final boolean sectionAtStartConnectsToStart; + private final boolean sectionAtEndConnectsToStart; + + private Section sectionAtStart; + private Section sectionAtEnd; + + public TransferPosition(Vector3 location, Quaternion orientation, int moveTicks, String sectionAtStartReference, String sectionAtEndReference, boolean sectionAtStartForwards, boolean sectionAtEndForwards, boolean sectionAtStartConnectsToStart, boolean sectionAtEndConnectsToStart) { + this.location = location; + this.orientation = orientation; + this.moveTicks = moveTicks; + this.sectionAtStartReference = sectionAtStartReference; + this.sectionAtEndReference = sectionAtEndReference; + this.sectionAtStartForwards = sectionAtStartForwards; + this.sectionAtEndForwards = sectionAtEndForwards; + this.sectionAtStartConnectsToStart = sectionAtStartConnectsToStart; + this.sectionAtEndConnectsToStart = sectionAtEndConnectsToStart; + + this.sectionAtStart = null; + this.sectionAtEnd = null; + } + + public Vector3 getLocation() { + return location; + } + + public Quaternion getOrientation() { + return orientation; + } + + public int getMoveTicks() { + return moveTicks; + } + + public String getSectionAtEndReference() { + return sectionAtEndReference; + } + + public String getSectionAtStartReference() { + return sectionAtStartReference; + } + + public Section getSectionAtStart() { + return sectionAtStart; + } + + public void setSectionAtStart(Section sectionAtStart) { + this.sectionAtStart = sectionAtStart; + } + + public Section getSectionAtEnd() { + return sectionAtEnd; + } + + public void setSectionAtEnd(Section sectionAtEnd) { + this.sectionAtEnd = sectionAtEnd; + } + + public boolean isSectionAtEndForwards() { + return sectionAtEndForwards; + } + + public boolean isSectionAtStartForwards() { + return sectionAtStartForwards; + } + + public boolean isSectionAtStartConnectsToStart() { + return sectionAtStartConnectsToStart; + } + + public boolean isSectionAtEndConnectsToStart() { + return sectionAtEndConnectsToStart; + } + + @Override + public String toString() { + return ""; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/count/RideCounterListener.java b/src/main/java/com/jverbruggen/jrides/models/ride/count/RideCounterListener.java new file mode 100644 index 00000000..2197289f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/count/RideCounterListener.java @@ -0,0 +1,39 @@ +package com.jverbruggen.jrides.models.ride.count; + +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.api.JRidesRide; +import com.jverbruggen.jrides.event.player.PlayerFinishedRideEvent; +import com.jverbruggen.jrides.event.player.PlayerQuitEvent; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.RideCounterManager; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class RideCounterListener implements Listener { + private final RideCounterManager rideCounterManager; + + public RideCounterListener() { + rideCounterManager = ServiceProvider.getSingleton(RideCounterManager.class); + } + + @EventHandler + public void onFinishRide(PlayerFinishedRideEvent event){ + JRidesPlayer player = event.getPlayer(); + JRidesRide ride = event.getRide(); + + RideCounterRecordCollection collection = rideCounterManager.getCollection(player.getIdentifier()); + RideCounterRecord record = collection.findOrCreate(ride.getIdentifier(), player); + + record.addOne(); + + rideCounterManager.sendRideCounterUpdateMessage(player, record); + rideCounterManager.saveToFile(player.getIdentifier(), collection); + } + + @EventHandler + public void onPlayerQuit(PlayerQuitEvent event){ + JRidesPlayer player = event.getPlayer(); + + rideCounterManager.saveAndUnload(player.getIdentifier()); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/count/RideCounterRecord.java b/src/main/java/com/jverbruggen/jrides/models/ride/count/RideCounterRecord.java new file mode 100644 index 00000000..8de43229 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/count/RideCounterRecord.java @@ -0,0 +1,94 @@ +package com.jverbruggen.jrides.models.ride.count; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.models.ride.Ride; +import com.jverbruggen.jrides.models.ride.UnloadedRide; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.RideManager; +import org.bukkit.configuration.serialization.ConfigurationSerializable; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +public class RideCounterRecord implements ConfigurationSerializable { + private final Ride ride; + private final UUID playerUUID; + private String playerName; + private int rideCount; + + public RideCounterRecord(Ride ride, String playerName, UUID playerUUID, int rideCount) { + this.ride = ride; + this.playerUUID = playerUUID; + this.playerName = playerName; + this.rideCount = rideCount; + } + + public boolean isActive(){ + return this.ride.isLoaded(); + } + + public Ride getRide() { + return ride; + } + + public String getRideIdentifier(){ + return ride.getIdentifier(); + } + + public int getRideCount() { + return rideCount; + } + + public UUID getPlayerUUID() { + return playerUUID; + } + + public String getPlayerName() { + return playerName; + } + + public void addOne(){ + rideCount++; + } + + @Override + public Map serialize() { + Map config = new HashMap<>(); + + config.put("rideIdentifier", this.ride.getIdentifier()); + config.put("playerName", this.playerName); + config.put("playerUUID", this.playerUUID.toString()); + config.put("rideCount", this.rideCount); + + return config; + } + + public static RideCounterRecord deserialize(Map config){ + String rideIdentifier = (String) config.get("rideIdentifier"); + + RideHandle rideHandle = ServiceProvider.getSingleton(RideManager.class) + .getRideHandle(rideIdentifier); + Ride ride; + if(rideHandle != null) ride = rideHandle.getRide(); + else ride = new UnloadedRide(rideIdentifier); + + int rideCount = (int) config.get("rideCount"); + String playerName = (String) config.get("playerName"); + String playerUUID = (String) config.get("playerUUID"); + + return new RideCounterRecord(ride, playerName, UUID.fromString(playerUUID), rideCount); + } + + public boolean sameIdentityAs(RideCounterRecord otherRecord){ + if(otherRecord == this) return true; + + return otherRecord.getPlayerUUID() == this.playerUUID + && otherRecord.getRideIdentifier().equalsIgnoreCase(this.getRideIdentifier()); + } + + public void updateTo(RideCounterRecord otherRecord){ + this.rideCount = otherRecord.rideCount; + this.playerName = otherRecord.playerName; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/count/RideCounterRecordCollection.java b/src/main/java/com/jverbruggen/jrides/models/ride/count/RideCounterRecordCollection.java new file mode 100644 index 00000000..4e69669a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/count/RideCounterRecordCollection.java @@ -0,0 +1,70 @@ +package com.jverbruggen.jrides.models.ride.count; + +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.ride.Ride; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.RideManager; +import org.bukkit.configuration.serialization.ConfigurationSerializable; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +public class RideCounterRecordCollection implements ConfigurationSerializable { + private Map records; + private String playerIdentifier; + + public RideCounterRecordCollection(Map records, String playerIdentifier) { + this.records = records; + this.playerIdentifier = playerIdentifier; + } + + public RideCounterRecordCollection(String playerIdentifier) { + this.records = new HashMap<>(); + this.playerIdentifier = playerIdentifier; + } + + public RideCounterRecord findOrCreate(String rideIdentifier, JRidesPlayer player){ + RideCounterRecord record = this.records.get(rideIdentifier); + if(record == null){ + Ride ride = ServiceProvider.getSingleton(RideManager.class) + .getRideHandle(rideIdentifier) + .getRide(); + + record = new RideCounterRecord(ride, player.getName(), player.getUniqueId(), 0); + this.records.put(rideIdentifier, record); + } + + return record; + } + + public Map getRecords() { + return records; + } + + public String getPlayerIdentifier() { + return playerIdentifier; + } + + @Override + public Map serialize() { + Map config = new HashMap<>(); + + config.put("records", List.of(this.records.values().toArray())); + config.put("playerIdentifier", this.playerIdentifier); + + return config; + } + + public static RideCounterRecordCollection deserialize(Map config){ + List recordsList = (List) config.get("records"); + String playerIdentifier = (String) config.get("playerIdentifier"); + + Map records = recordsList.stream() + .collect(Collectors.toMap(RideCounterRecord::getRideIdentifier, r->r)); + + return new RideCounterRecordCollection(records, playerIdentifier); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/count/RideCounterRecordRideCollection.java b/src/main/java/com/jverbruggen/jrides/models/ride/count/RideCounterRecordRideCollection.java new file mode 100644 index 00000000..d56b4ea9 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/count/RideCounterRecordRideCollection.java @@ -0,0 +1,101 @@ +package com.jverbruggen.jrides.models.ride.count; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.RideManager; +import org.bukkit.configuration.serialization.ConfigurationSerializable; + +import java.util.*; + +/** + * Ride-bound ride counter record collection. + * Used for saving 'top x records' bound to a ride. + * Only a few records apply for being present on this board. + */ +public class RideCounterRecordRideCollection implements ConfigurationSerializable { + private final List records; + private final RideHandle rideHandle; + + public RideCounterRecordRideCollection(List records, RideHandle rideHandle) { + this.records = records; + this.rideHandle = rideHandle; + } + + public RideCounterRecordRideCollection(RideHandle rideHandle) { + this.records = new ArrayList<>(); + this.rideHandle = rideHandle; + } + + private RideCounterRecord findSimilarRecord(RideCounterRecord record){ + return this.records.stream().filter(r -> r.sameIdentityAs(record)).findFirst().orElse(null); + } + + public boolean existsOn(JRidesPlayer player){ + Optional record = this.records.stream().filter(r -> r.getPlayerUUID().equals(player.getUniqueId())).findFirst(); + return record.isPresent(); + } + + public boolean existsOn(RideCounterRecord record){ + return this.records.stream().anyMatch(r -> r.sameIdentityAs(record)); + } + + public List getRecords() { + return records; + } + + public boolean update(RideCounterRecord record){ + if(!appliesToThisCollection(record)) return false; + + RideCounterRecord foundRecord = records.stream().filter(r -> r.sameIdentityAs(record)).findFirst().orElse(null); + if(foundRecord == null) return false; + + foundRecord.updateTo(record); + return true; + } + + public void add(RideCounterRecord record){ + if(!appliesToThisCollection(record)) return; + + records.add(record); + } + + public boolean remove(RideCounterRecord record){ + if(!appliesToThisCollection(record)) return false; + + if(records.contains(record)){ + records.remove(record); + return true; + } + + RideCounterRecord foundRecord = findSimilarRecord(record); + if(foundRecord != null){ + records.remove(foundRecord); + return true; + } + + return false; + } + + @Override + public Map serialize() { + Map config = new HashMap<>(); + + config.put("records", records); + config.put("rideIdentifier", this.rideHandle.getRide().getIdentifier()); + + return config; + } + + public static RideCounterRecordRideCollection deserialize(Map config){ + List records = (List) config.get("records"); + String rideIdentifier = (String) config.get("rideIdentifier"); + RideHandle rideHandle = ServiceProvider.getSingleton(RideManager.class).getRideHandle(rideIdentifier); + + return new RideCounterRecordRideCollection(records, rideHandle); + } + + private boolean appliesToThisCollection(RideCounterRecord record){ + return record.getRide().getIdentifier().equalsIgnoreCase(rideHandle.getRide().getIdentifier()); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/factory/ConfigAdvancedSplineTrackFactory.java b/src/main/java/com/jverbruggen/jrides/models/ride/factory/ConfigAdvancedSplineTrackFactory.java new file mode 100644 index 00000000..68cda722 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/factory/ConfigAdvancedSplineTrackFactory.java @@ -0,0 +1,108 @@ +package com.jverbruggen.jrides.models.ride.factory; + +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.animator.coaster.NoLimitsExportPositionRecord; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.factory.TrackBehaviourFactory; +import com.jverbruggen.jrides.config.coaster.CoasterConfig; +import com.jverbruggen.jrides.config.coaster.objects.TrackConfig; +import com.jverbruggen.jrides.config.coaster.objects.section.base.SectionConfig; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.frame.factory.FrameFactory; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.track.compound.CompoundTrack; +import com.jverbruggen.jrides.models.ride.coaster.track.compound.LooseEndedSplineBasedTrack; +import com.jverbruggen.jrides.models.ride.factory.track.TrackDescription; +import com.jverbruggen.jrides.models.ride.factory.track.TrackType; +import com.jverbruggen.jrides.models.ride.section.builder.AdvancedSectionBuilder; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; + +import java.util.ArrayList; +import java.util.List; + +public class ConfigAdvancedSplineTrackFactory implements TrackFactory { + private final TrackBehaviourFactory trackBehaviourFactory; + private final FrameFactory frameFactory; + + private final CoasterHandle coasterHandle; + private final CoasterConfig coasterConfig; + private final List trackDescriptions; + + public ConfigAdvancedSplineTrackFactory(CoasterHandle coasterHandle, CoasterConfig coasterConfig, List trackDescriptions) { + this.coasterHandle = coasterHandle; + this.coasterConfig = coasterConfig; + this.trackDescriptions = trackDescriptions; + this.trackBehaviourFactory = ServiceProvider.getSingleton(TrackBehaviourFactory.class); + this.frameFactory = ServiceProvider.getSingleton(FrameFactory.class); + } + + @Override + public Track createTrack(){ + // --- Calculate sections + TrackConfig trackConfig = coasterConfig.getTrack(); + AdvancedSectionBuilder sectionBuilder = createSectionBuilder(trackConfig); + + // --- Assemble tracks + List childrenTracks = new ArrayList<>(); + for(TrackDescription trackDescription : trackDescriptions){ + Track track; + if(trackDescription.getTrackType() == TrackType.TRACK){ + track = createSplineTrack(trackDescription, sectionBuilder); + }else throw new RuntimeException("TrackType not recognized"); + + childrenTracks.add(track); + } + + // --- Tie track and section ends together + Track prevTrack = null; + Track firstTrack = null; + for(int i = 0; i < childrenTracks.size(); i++){ + Track track = childrenTracks.get(i); + if(firstTrack == null) firstTrack = track; + boolean isLast = i == childrenTracks.size()-1; + + if(prevTrack != null){ + prevTrack.setNextTrack(track); + track.setPreviousTrack(prevTrack); + } + if(isLast){ + track.setNextTrack(firstTrack); + firstTrack.setPreviousTrack(track); + } + + prevTrack = track; + } + + return new CompoundTrack(childrenTracks); + } + + public Track createSplineTrack(TrackDescription trackDescription, AdvancedSectionBuilder sectionBuilder){ + List positions = trackDescription.getPositions(); + + String parentTrackIdentifier = trackDescription.getIdentifier(); + Frame startFrame = trackDescription.getStartFrame(); + Frame endFrame = trackDescription.getEndFrame(); + + Track track = new LooseEndedSplineBasedTrack(trackDescription.getIdentifier(), positions, sectionBuilder.collectFor(parentTrackIdentifier), + startFrame, endFrame); + + startFrame.setTrack(track); + endFrame.setTrack(track); + + return track; + } + + private AdvancedSectionBuilder createSectionBuilder(TrackConfig trackConfig){ + AdvancedSectionBuilder sectionBuilder = new AdvancedSectionBuilder(); + List sectionConfigs = trackConfig.getSections(); + + for(int i = 0; i < sectionConfigs.size(); i++){ + sectionBuilder.add(sectionConfigs.get(i).build(trackBehaviourFactory, trackDescriptions, coasterHandle, coasterConfig)); + } + + sectionBuilder.calculate(); + sectionBuilder.populateTransfers(coasterHandle.getTransfers()); + sectionBuilder.populateBehaviours(); + + return sectionBuilder; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/factory/SeatFactory.java b/src/main/java/com/jverbruggen/jrides/models/ride/factory/SeatFactory.java new file mode 100644 index 00000000..db27026e --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/factory/SeatFactory.java @@ -0,0 +1,76 @@ +package com.jverbruggen.jrides.models.ride.factory; + +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Matrix4x4; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.math.Vector3PlusYaw; +import com.jverbruggen.jrides.models.ride.seat.Seat; +import com.jverbruggen.jrides.models.ride.coaster.train.CoasterSeat; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.viewport.ViewportManager; + +import java.util.ArrayList; +import java.util.List; + +public class SeatFactory { + private final ViewportManager viewportManager; + + public SeatFactory() { + this.viewportManager = ServiceProvider.getSingleton(ViewportManager.class); + } + + public List createCoasterSeats(CoasterHandle coasterHandle, List seatOffsets, Vector3 cartLocation, Quaternion orientation){ + List seats = new ArrayList<>(); + Matrix4x4 rotationMatrix = new Matrix4x4(); + rotationMatrix.rotate(orientation); + + for(Vector3PlusYaw seatOffset : seatOffsets){ + Vector3 relativeSeatLocation = calculateSeatLocationOnMatrix(rotationMatrix, seatOffset); + Vector3 absoluteSeatLocation = Vector3.add(cartLocation, relativeSeatLocation); + + double yawRotation = orientation.getPacketYaw(); + yawRotation += seatOffset.getYaw(); + + VirtualEntity seatEntity = viewportManager.spawnSeatEntity(absoluteSeatLocation, yawRotation, null); + CoasterSeat seat = new CoasterSeat(coasterHandle, seatEntity, seatOffset); + seatEntity.setHostSeat(seat); + seats.add(seat); + } + return seats; + } + + private static Vector3 calculateSeatLocationOnMatrix(Matrix4x4 alreadyRotatedMatrix, Vector3PlusYaw seatOffset){ + final Vector3 heightCompensationVector = CoasterSeat.getHeightCompensation(); + Vector3 compensatedSeatOffset = Vector3.add(seatOffset, heightCompensationVector); + alreadyRotatedMatrix.translate(compensatedSeatOffset); + + Vector3 relativeSeatLocation = alreadyRotatedMatrix.toVector3(); + Vector3 compensatedRelativeSeatLocation = Vector3.subtract(relativeSeatLocation, heightCompensationVector); + + alreadyRotatedMatrix.translate(compensatedSeatOffset.negate()); + return compensatedRelativeSeatLocation; + } + + public static void moveCoasterSeats(List seats, Vector3 cartLocation, Quaternion orientation){ + Matrix4x4 rotationMatrix = new Matrix4x4(); + rotationMatrix.rotate(orientation); + + for(Seat seat : seats){ + Vector3PlusYaw seatOffset = seat.getOffset(); + Vector3 relativeSeatLocation = calculateSeatLocationOnMatrix(rotationMatrix, seatOffset); + Vector3 absoluteSeatLocation = Vector3.add(cartLocation, relativeSeatLocation); + + double yaw = seatOffset.getYaw(); + orientation.rotateYawPitchRoll(0, yaw, 0); + seat.setLocation(absoluteSeatLocation, orientation); + orientation.rotateYawPitchRoll(0, -yaw, 0); + } + } + + public static void moveFlatRideSeat(Seat seat, Matrix4x4 positionMatrix, Quaternion endRotation){ + Vector3 position = calculateSeatLocationOnMatrix(positionMatrix, Vector3PlusYaw.zero()); + seat.setLocation(position, endRotation); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/factory/TrackFactory.java b/src/main/java/com/jverbruggen/jrides/models/ride/factory/TrackFactory.java new file mode 100644 index 00000000..2d4f808b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/factory/TrackFactory.java @@ -0,0 +1,7 @@ +package com.jverbruggen.jrides.models.ride.factory; + +import com.jverbruggen.jrides.models.ride.coaster.track.Track; + +public interface TrackFactory { + Track createTrack(); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/factory/TrainFactory.java b/src/main/java/com/jverbruggen/jrides/models/ride/factory/TrainFactory.java new file mode 100644 index 00000000..de5f898b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/factory/TrainFactory.java @@ -0,0 +1,135 @@ +package com.jverbruggen.jrides.models.ride.factory; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.config.coaster.CoasterConfig; +import com.jverbruggen.jrides.config.coaster.objects.CartSpecConfig; +import com.jverbruggen.jrides.config.coaster.objects.VehiclesConfig; +import com.jverbruggen.jrides.config.coaster.objects.item.ItemConfig; +import com.jverbruggen.jrides.config.coaster.objects.cart.CartTypeSpecConfig; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.math.Vector3PlusYaw; +import com.jverbruggen.jrides.models.math.VectorQuaternionState; +import com.jverbruggen.jrides.models.properties.frame.AutoTrackUpdateFrame; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.*; +import com.jverbruggen.jrides.models.ride.section.Section; +import com.jverbruggen.jrides.models.ride.section.provider.SectionProvider; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.viewport.ViewportManager; +import org.bukkit.Bukkit; + +import java.util.ArrayList; +import java.util.List; + +public class TrainFactory { + private final ViewportManager viewportManager; + private final SeatFactory seatFactory; + private final SectionProvider sectionProvider; + + public TrainFactory() { + this.viewportManager = ServiceProvider.getSingleton(ViewportManager.class); + this.seatFactory = ServiceProvider.getSingleton(SeatFactory.class); + this.sectionProvider = ServiceProvider.getSingleton(SectionProvider.class); + } + + public Train createEquallyDistributedTrain(CoasterHandle coasterHandle, Track track, CoasterConfig coasterConfig, String trainIdentifier){ + final Section spawnSection = track.getNextSpawnSection(); + if(spawnSection == null){ + JRidesPlugin.getLogger().severe("No spawn section available on track " + track + " for train " + trainIdentifier + " to spawn!"); + return null; + } + + VehiclesConfig vehiclesConfig = coasterConfig.getVehicles(); + + final int amountOfCarts = vehiclesConfig.getCarts(); + final int cartDistance = vehiclesConfig.getCartDistance(); + + final Frame sectionSpawnFrame = spawnSection.getSpawnFrame(); + final int headOfTrainFrameValue = sectionSpawnFrame.getValue(); + final int middleOfTrainFrameValue = headOfTrainFrameValue - (amountOfCarts*cartDistance) / 2; + final int tailOfTrainFrameValue = headOfTrainFrameValue - (amountOfCarts*cartDistance); + + final Track spawnTrack = sectionSpawnFrame.getTrack(); + + final Frame headOfTrainFrame = new AutoTrackUpdateFrame(headOfTrainFrameValue, spawnTrack, spawnSection); + final Frame middleOfTrainFrame = new AutoTrackUpdateFrame(middleOfTrainFrameValue, spawnTrack, spawnSection); + final Frame tailOfTrainFrame = new AutoTrackUpdateFrame(tailOfTrainFrameValue, spawnTrack, spawnSection); + + final Vector3 cartOffset = coasterConfig.getCartSpec().getDefault().getModel().getPosition(); + final Quaternion cartRotationOffset = coasterConfig.getCartSpec().getDefault().getModel().getRotation(); + + List carts = new ArrayList<>(); + for(int i = 0; i < amountOfCarts; i++){ + int cartOffsetFrames = i*cartDistance; + if(amountOfCarts == 1) + cartOffsetFrames += cartDistance/2; + + Frame cartFrame = headOfTrainFrame.clone().add(-cartOffsetFrames); + + CartSpecConfig cartSpecConfig = coasterConfig.getCartSpec(); + CartTypeSpecConfig cartTypeSpecConfig; + if(i == 0 && cartSpecConfig.hasHead()) + cartTypeSpecConfig = cartSpecConfig.getHead(); + else if(i == amountOfCarts-1 && cartSpecConfig.hasTail()) + cartTypeSpecConfig = cartSpecConfig.getTail(); + else + cartTypeSpecConfig = cartSpecConfig.getDefault(); + + ItemConfig cartModelItemConfig = cartTypeSpecConfig.getModel().getItemConfig(); + + Vector3 trackLocation = spawnSection.getLocationFor(cartFrame); + Quaternion orientation = spawnSection.getOrientationFor(cartFrame); + + VectorQuaternionState vectorQuaternionState = CoasterCart.calculateLocation(trackLocation, cartOffset, orientation, cartRotationOffset); + Vector3 cartLocation = vectorQuaternionState.getVector(); + Quaternion cartOrientation = vectorQuaternionState.getQuaternion(); + + VirtualEntity virtualEntity = cartModelItemConfig.spawnEntity(viewportManager, cartLocation, cartOrientation, null); + Bukkit.getScheduler().runTask(JRidesPlugin.getBukkitPlugin(), () -> virtualEntity.setRotation(cartOrientation)); + + List seatOffsets = cartTypeSpecConfig.getSeats().getPositions(); + List seats = seatFactory.createCoasterSeats(coasterHandle, seatOffsets, cartLocation, cartOrientation); + + Section cartSection = spawnSection; + if(!cartSection.isInSection(cartFrame)){ + cartSection = sectionProvider.findSectionBySearchingPrevious(null, cartFrame, spawnSection); + if(cartSection == null) + throw new RuntimeException("Cant find where cart index=" + i + " should be placed (section-wise)"); + } + + String cartName = trainIdentifier + "_cart_" + i; + CoasterCart cart = new SimpleCoasterCart( + cartName, + seats, + virtualEntity, + cartOffset, + cartRotationOffset, + cartFrame); + carts.add(cart); + } + + Vector3 headLocation = track.getLocationFor(headOfTrainFrame); + Vector3 middleLocation = track.getLocationFor(middleOfTrainFrame); + Vector3 tailLocation = track.getLocationFor(tailOfTrainFrame); + + boolean debugMode = coasterConfig.isDebugMode(); + if(debugMode) + JRidesPlugin.getLogger().warning("Ride " + coasterConfig.getIdentifier() + " is in DEBUG mode! Disable this to make this message disappear."); + + Train train = new SimpleTrain(trainIdentifier, carts, headOfTrainFrame, middleOfTrainFrame, tailOfTrainFrame, + headLocation, middleLocation, tailLocation, spawnSection, debugMode); + spawnSection.setLocalReservation(train); + spawnSection.addOccupation(train); + + return train; + } + + public void unloadAll(List trainHandles) { + viewportManager.removeEntities(trainHandles); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/factory/track/TrackDescription.java b/src/main/java/com/jverbruggen/jrides/models/ride/factory/track/TrackDescription.java new file mode 100644 index 00000000..7263583d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/factory/track/TrackDescription.java @@ -0,0 +1,47 @@ +package com.jverbruggen.jrides.models.ride.factory.track; + +import com.jverbruggen.jrides.animator.coaster.NoLimitsExportPositionRecord; +import com.jverbruggen.jrides.models.properties.frame.Frame; + +import java.util.List; + +public class TrackDescription { + private final String identifier; + private final List positions; + private final TrackType trackType; + private final Frame startFrame; + private final Frame endFrame; + + public TrackDescription(String identifier, List positions, TrackType trackType, Frame startFrame, Frame endFrame) { + this.identifier = identifier; + this.positions = positions; + this.trackType = trackType; + this.startFrame = startFrame; + this.endFrame = endFrame; + } + + public String getIdentifier() { + return identifier; + } + + public List getPositions() { + return positions; + } + + public TrackType getTrackType() { + return trackType; + } + + public Frame getStartFrame() { + return startFrame; + } + + public Frame getEndFrame() { + return endFrame; + } + + public int getCycle(){ + return getPositions().size()-1; + } +} + diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/factory/track/TrackType.java b/src/main/java/com/jverbruggen/jrides/models/ride/factory/track/TrackType.java new file mode 100644 index 00000000..d281521e --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/factory/track/TrackType.java @@ -0,0 +1,6 @@ +package com.jverbruggen.jrides.models.ride.factory.track; + +public enum TrackType { + TRACK, + TRANSFER +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/factory/train/TrainCreationResult.java b/src/main/java/com/jverbruggen/jrides/models/ride/factory/train/TrainCreationResult.java new file mode 100644 index 00000000..f73751a9 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/factory/train/TrainCreationResult.java @@ -0,0 +1,10 @@ +package com.jverbruggen.jrides.models.ride.factory.train; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; + +import javax.annotation.Nonnull; +import java.util.List; + +public record TrainCreationResult(@Nonnull List output, boolean success) { + +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/flatride/FlatRide.java b/src/main/java/com/jverbruggen/jrides/models/ride/flatride/FlatRide.java new file mode 100644 index 00000000..f096ef28 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/flatride/FlatRide.java @@ -0,0 +1,13 @@ +package com.jverbruggen.jrides.models.ride.flatride; + +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.ride.AbstractRide; +import org.bukkit.inventory.ItemStack; + +import java.util.List; + +public class FlatRide extends AbstractRide { + public FlatRide(String identifier, String displayName, List displayDescription, ItemStack displayItem, PlayerLocation warpLocation, boolean canExitDuringRide) { + super(identifier, displayName, displayDescription, displayItem, warpLocation, canExitDuringRide); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/flatride/PlayerControl.java b/src/main/java/com/jverbruggen/jrides/models/ride/flatride/PlayerControl.java new file mode 100644 index 00000000..73da8f99 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/flatride/PlayerControl.java @@ -0,0 +1,49 @@ +package com.jverbruggen.jrides.models.ride.flatride; + +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.models.ride.seat.InstructionType; + +public interface PlayerControl { + /** + * This function is called out of the bukkit main thread. + * To avoid spamming of instruction, it is required to debounce + * incoming instructions. + * @param instruction Incoming instruction of player + */ + void processInstructionAsync(InstructionType instruction); + + /** + * Called by synchronized bukkit thread + * to apply control to the component + */ + void apply(); + + /** + * Reset the player control + */ + void reset(); + + /** + * Add player that controls the PlayerControl + * Used for communication + * @param player player to add + */ + void addControlling(JRidesPlayer player); + + /** + * Remove player that controls the PlayerControl + * Used for communication + * @param player player to remove + */ + void removeControlling(JRidesPlayer player); + + /** + * Send notification that the control phase has started + */ + void sendStartNotification(); + + /** + * Send notification that the control phase has stopped + */ + void sendStopNotification(); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/gate/FenceGate.java b/src/main/java/com/jverbruggen/jrides/models/ride/gate/FenceGate.java new file mode 100644 index 00000000..273385fe --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/gate/FenceGate.java @@ -0,0 +1,64 @@ +package com.jverbruggen.jrides.models.ride.gate; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.control.DispatchLock; +import org.bukkit.Sound; +import org.bukkit.block.Block; +import org.bukkit.block.data.BlockData; +import org.bukkit.block.data.Openable; + +public class FenceGate implements Gate { + private final String name; + private final DispatchLock dispatchLock; + private final Block block; + private boolean isOpen; + + public FenceGate(String name, DispatchLock dispatchLock, Block block) { + this.name = name; + this.dispatchLock = dispatchLock; + this.block = block; + this.isOpen = false; + } + + public String getName() { + return name; + } + + @Override + public void open() { + if(isOpen) return; + + isOpen = true; + dispatchLock.lock(); + setBukkitGateState(true); + } + + @Override + public void close() { + if(!isOpen) return; + + isOpen = false; + dispatchLock.unlock(); + setBukkitGateState(false); + } + + @Override + public boolean isOpen() { + return this.isOpen; + } + + private void setBukkitGateState(boolean open){ + BlockData blockData = block.getBlockData(); + if(!(blockData instanceof org.bukkit.block.data.type.Gate)){ + JRidesPlugin.getLogger().severe("Fence gate " + name + " not positioned over actual fence gate block (location: " + block.getLocation() + ")"); + return; + } + + Openable bukkitGate = (Openable) blockData; + bukkitGate.setOpen(open); + block.setBlockData(bukkitGate); + + Sound sound = open ? Sound.BLOCK_FENCE_GATE_OPEN : Sound.BLOCK_FENCE_GATE_CLOSE; + block.getWorld().playSound(block.getLocation(), sound, 1, 1); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/gate/Gate.java b/src/main/java/com/jverbruggen/jrides/models/ride/gate/Gate.java new file mode 100644 index 00000000..b831acce --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/gate/Gate.java @@ -0,0 +1,7 @@ +package com.jverbruggen.jrides.models.ride.gate; + +public interface Gate { + void open(); + void close(); + boolean isOpen(); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/gate/GateType.java b/src/main/java/com/jverbruggen/jrides/models/ride/gate/GateType.java new file mode 100644 index 00000000..b2759db7 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/gate/GateType.java @@ -0,0 +1,24 @@ +package com.jverbruggen.jrides.models.ride.gate; + +public enum GateType { + // Simple gate + DOOR_OR_GATE, + + // Door block animations + VANISH_BLOCK_DOOR, + ANIMATED_BLOCK_DOOR, + + // If gate opening and closing is done by external logic (relying on feedback from that logic through events/notifications) + EXTERNAL; + + public static GateType fromValue(String value){ + switch(value){ + case "default": + case "door": + case "gate": + return GateType.DOOR_OR_GATE; + default: + throw new RuntimeException("Gate type " + value + " is (currently) not supported"); + } + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/seat/AbstractSeat.java b/src/main/java/com/jverbruggen/jrides/models/ride/seat/AbstractSeat.java new file mode 100644 index 00000000..f7b8185b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/seat/AbstractSeat.java @@ -0,0 +1,170 @@ +package com.jverbruggen.jrides.models.ride.seat; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.event.player.PlayerStandUpEvent; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.SeatedOnContext; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.math.Vector3PlusYaw; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.ride.flatride.PlayerControl; +import com.jverbruggen.jrides.state.ride.SoftEjector; + +import javax.annotation.Nonnull; + +public abstract class AbstractSeat implements Seat { + private final RideHandle parentRideHandle; + private Player passenger; + private final VirtualEntity virtualEntity; + private final Vector3PlusYaw offset; + private boolean restraintLocked; + private SeatHost seatHost; + + public AbstractSeat(RideHandle parentRideHandle, SeatHost seatHost, VirtualEntity virtualEntity, Vector3PlusYaw offset) { + this.parentRideHandle = parentRideHandle; + this.seatHost = seatHost; + this.passenger = null; + this.virtualEntity = virtualEntity; + this.offset = offset; + this.restraintLocked = true; + } + + @Override + public void setParentSeatHost(SeatHost seatHost) { + this.seatHost = seatHost; + } + + @Override + public SeatHost getParentSeatHost() { + return seatHost; + } + + @Override + public Player getPassenger() { + return passenger; + } + + @Override + public boolean hasPassenger() { + return passenger != null; + } + + @Override + public void setPassenger(Player player) { + VirtualEntity virtualArmorstand = getEntity(); + Player passenger = getPassenger(); + + if(passenger != null){ // Overtaking seat or player = null + if(passenger == player) return; + + onPassengerExit(passenger); + } + + this.passenger = player; + virtualArmorstand.setPassenger(player); + if(player != null){ + if(!player.hasPermission(Permissions.RIDE_ENTER)){ + JRidesPlugin.getLanguageFile().sendMessage(player, LanguageFileField.ERROR_GENERAL_NO_PERMISSION_MESSAGE); + return; + } + + onPassengerEnter(player); + } + } + + @Override + public boolean ejectPassengerSoft(boolean teleport) { + if(!hasPassenger()) return false; + Player passenger = getPassenger(); + + if(SoftEjector.hasTimer(passenger)){ + SoftEjector.removeTimer(passenger); + setPassenger(null); + if(teleport){ + PlayerLocation ejectLocation = getParentSeatHost().getEjectLocation(); + passenger.teleport(ejectLocation, true); + } + return true; + }else{ + SoftEjector.addTimer(passenger); + JRidesPlugin.getLanguageFile().sendMessage(passenger, LanguageFileField.NOTIFICATION_SHIFT_EXIT_CONFIRMATION); + return false; + } + } + + @Override + public Vector3PlusYaw getOffset() { + return offset; + } + + @Override + public void setLocation(Vector3 location, Quaternion orientation) { + virtualEntity.setLocation(location); + virtualEntity.setRotation(orientation); + + if(hasPassenger()){ + Quaternion smoothAnimationRotation = orientation.clone(); + smoothAnimationRotation.rotateY(90); + passenger.setSmoothAnimationRotation(smoothAnimationRotation); + } + } + + @Override + public VirtualEntity getEntity() { + return virtualEntity; + } + + @Override + public void setRestraint(boolean locked) { + restraintLocked = locked; + } + + @Override + public boolean restraintsActive() { + return restraintLocked; + } + + @Override + public RideHandle getParentRideHandle() { + return parentRideHandle; + } + + @Override + public boolean supportsPlayerControl() { + return false; + } + + @Nonnull + @Override + public PlayerControl getPlayerControl() { + throw new RuntimeException("Unimplemented player control"); + } + + @Override + public void sendPlayerControlInstruction(InstructionType instruction) { + // Do nothing + } + + protected void onPassengerExit(Player passenger){ + SeatedOnContext seatedOnContext = passenger.getSeatedOnContext(); + if(seatedOnContext != null) + seatedOnContext.restore(passenger); + + virtualEntity.setPassenger(null); + PlayerStandUpEvent.send(passenger, getParentSeatHost().getRideHandle().getRide()); + + seatHost.onPlayerExit(passenger); + } + + protected void onPassengerEnter(Player passenger){ + SeatedOnContext seatedOnContext = SeatedOnContext.create(this, passenger); + seatedOnContext.setup(passenger); + + seatHost.onPlayerEnter(passenger); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/seat/InstructionType.java b/src/main/java/com/jverbruggen/jrides/models/ride/seat/InstructionType.java new file mode 100644 index 00000000..b3840efd --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/seat/InstructionType.java @@ -0,0 +1,10 @@ +package com.jverbruggen.jrides.models.ride.seat; + +public enum InstructionType { + NONE, + A, + D, + W, + S, + SPACE +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/seat/PlayerControlInstruction.java b/src/main/java/com/jverbruggen/jrides/models/ride/seat/PlayerControlInstruction.java new file mode 100644 index 00000000..631416c6 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/seat/PlayerControlInstruction.java @@ -0,0 +1,6 @@ +package com.jverbruggen.jrides.models.ride.seat; + +import com.jverbruggen.jrides.models.entity.Player; + +public record PlayerControlInstruction(InstructionType instructionType, Player player) { +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/seat/Seat.java b/src/main/java/com/jverbruggen/jrides/models/ride/seat/Seat.java new file mode 100644 index 00000000..55784bc3 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/seat/Seat.java @@ -0,0 +1,34 @@ +package com.jverbruggen.jrides.models.ride.seat; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.math.Vector3PlusYaw; +import com.jverbruggen.jrides.models.ride.flatride.PlayerControl; + +import javax.annotation.Nonnull; + +public interface Seat { + Player getPassenger(); + void setPassenger(Player player); + boolean hasPassenger(); + boolean ejectPassengerSoft(boolean teleport); + + Vector3PlusYaw getOffset(); + void setLocation(Vector3 location, Quaternion orientation); + + VirtualEntity getEntity(); + void setRestraint(boolean locked); + boolean restraintsActive(); + + void setParentSeatHost(SeatHost seatHost); + SeatHost getParentSeatHost(); + + RideHandle getParentRideHandle(); + + boolean supportsPlayerControl(); + @Nonnull PlayerControl getPlayerControl(); + void sendPlayerControlInstruction(InstructionType instruction); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/seat/SeatHost.java b/src/main/java/com/jverbruggen/jrides/models/ride/seat/SeatHost.java new file mode 100644 index 00000000..4a37838f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/seat/SeatHost.java @@ -0,0 +1,21 @@ +package com.jverbruggen.jrides.models.ride.seat; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.ride.seat.Seat; + +import java.util.List; + +public interface SeatHost { + List getSeats(); + List getPassengers(); + void ejectPassengers(); + void despawn(); + void setRestraint(boolean locked); + boolean getRestraintState(); + PlayerLocation getEjectLocation(); + RideHandle getRideHandle(); + void onPlayerEnter(Player player); + void onPlayerExit(Player player); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/section/BaseSection.java b/src/main/java/com/jverbruggen/jrides/models/ride/section/BaseSection.java new file mode 100644 index 00000000..ad2c49fe --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/section/BaseSection.java @@ -0,0 +1,407 @@ +package com.jverbruggen.jrides.models.ride.section; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.TrackBehaviour; +import com.jverbruggen.jrides.logging.LogType; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.result.BlockSectionSafetyResult; +import org.checkerframework.checker.nullness.qual.NonNull; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public abstract class BaseSection implements Section{ + protected final TrackBehaviour trackBehaviour; + protected Track parentTrack; + + private Train reservedBy; + private Train occupiedBy; + private Section previousSection; + private Section nextSection; + private String arrivalUnlocks; + private final List
    additionalPreviousSections; + + public BaseSection(TrackBehaviour trackBehaviour) { + this.trackBehaviour = trackBehaviour; + this.reservedBy = null; + this.occupiedBy = null; + this.previousSection = null; + this.nextSection = null; + this.arrivalUnlocks = null; + this.parentTrack = null; + this.additionalPreviousSections = new ArrayList<>(); + } + + public void setArrivalUnlocks(String arrivalUnlocks) { + this.arrivalUnlocks = arrivalUnlocks; + } + + @Nullable + @Override + public Train getReservedBy() { + return reservedBy; + } + + @Override + public boolean canReserveLocally(@Nullable Train train) { + if(train == null) return reservedBy == null; + + if(trackBehaviour.canHandleBlockSectionSafety()) { + return ((SectionSafetyProvider)trackBehaviour).canHandleOccupation(train); + } + + boolean freeOfReservations = reservedBy == null || reservedBy == train; + boolean freeOfOccupation = occupiedBy == null || occupiedBy == train; + + return freeOfReservations && freeOfOccupation; + } + + @Override + public boolean canReserveEntireBlock(@Nonnull Train train) { + boolean canReserveLocally = canReserveLocally(train); + if(!canReserveLocally) return false; + + if(canBlock()) return true; + else return nextSection.canReserveEntireBlock(train); + } + + @Override + public void setEntireBlockReservation(@Nonnull Train train) { + if(canReserveLocally(train)){ + setLocalReservation(train); + }else throw new RuntimeException("Could not make reservation although committed to it"); + + if(!canBlock()) nextSection.setEntireBlockReservation(train); + } + + @Override + public void clearEntireBlockReservation(@Nonnull Train authority) { + clearEntireBlockReservation(authority, new ArrayList<>()); + } + + @Override + public void clearEntireBlockReservation(@Nonnull Train authority, List
    done) { + clearLocalReservation(authority); + done.add(this); + + if(!canBlock() && !done.contains(nextSection)) nextSection.clearEntireBlockReservation(authority, done); + + clearPreviousSectionReservation(authority, done, previousSection); + if(!additionalPreviousSections.isEmpty()) + additionalPreviousSections.forEach(s-> clearPreviousSectionReservation(authority, done,s)); + } + + private void clearPreviousSectionReservation(@Nonnull Train authority, List
    done, Section previousSection){ + if(previousSection == null) return; + + if(!previousSection.canBlock() && !done.contains(previousSection)){ + previousSection.clearEntireBlockReservation(authority, done); + }else{ + previousSection.clearLocalReservation(authority); + } + } + + @Override + public void setLocalReservation(@Nonnull Train train) { + if(trackBehaviour.canHandleBlockSectionSafety()) { + ((SectionSafetyProvider)trackBehaviour).handleNewReservation(train); + return; + } + + if(reservedBy == train) return; + if(reservedBy != null) + throw new RuntimeException("Cannot reserve an already-reserved section!"); + + reservedBy = train; + reservedBy.addReservedSection(this); +// Bukkit.broadcastMessage("Set reservation " + getName()); + } + + @Override + public void clearLocalReservation(@Nonnull Train authority) { + if(trackBehaviour.canHandleBlockSectionSafety()) { + ((SectionSafetyProvider)trackBehaviour).handleClearReservation(authority); + return; + } + + if(reservedBy == null) + return; + + if(reservedBy != authority){ +// Bukkit.broadcastMessage("Not authorised to clear reservation!"); + return; + } + + reservedBy.removeReservedSection(this); + reservedBy = null; +// Bukkit.broadcastMessage("Cleared reservation " + getName()); + } + + @Override + public boolean isReserved() { + if(trackBehaviour.canHandleBlockSectionSafety()) { + return ((SectionSafetyProvider)trackBehaviour).getReservation() != null; + } + + return reservedBy != null; + } + + @Override + public boolean isReservedBy(Train train) { + if(trackBehaviour.canHandleBlockSectionSafety()) { + return ((SectionSafetyProvider)trackBehaviour).isReservedBy(train); + } + + return reservedBy == train; + } + + @Override + public Train getOccupiedBy() { + return occupiedBy; + } + + @Override + public boolean isOccupied() { + if(trackBehaviour.canHandleBlockSectionSafety()){ + return ((SectionSafetyProvider)trackBehaviour).isOccupied(); + } + + return occupiedBy != null; + } + + @Override + public boolean isOccupiedBy(Train train) { + if(trackBehaviour.canHandleBlockSectionSafety()){ + return ((SectionSafetyProvider)trackBehaviour).isOccupiedBy(train); + } + return occupiedBy == train; + } + + @Override + public boolean canHandleOccupation(Train train) { + if(trackBehaviour.canHandleBlockSectionSafety()){ + return ((SectionSafetyProvider)trackBehaviour).canHandleOccupation(train); + } + + return getOccupiedBy().equals(train); + } + + @Override + public BlockSectionSafetyResult getBlockSectionSafety(@Nullable Train train) { + return getBlockSectionSafety(train, true); + } + + @Override + public Vector3 getLocationFor(Frame frame) { + if(trackBehaviour.definesNextSection()){ + return trackBehaviour.getBehaviourDefinedPosition(parentTrack.getLocationFor(frame)); + } + + return parentTrack.getLocationFor(frame); + } + + @Override + public Quaternion getOrientationFor(Frame frame) { + if(trackBehaviour.definesNextSection()){ + return trackBehaviour.getBehaviourDefinedOrientation(parentTrack.getOrientationFor(frame)); + } + return parentTrack.getOrientationFor(frame); + } + + @Override + public boolean addOccupation(@NonNull Train train) { + if(trackBehaviour.canHandleBlockSectionSafety()) { + ((SectionSafetyProvider)trackBehaviour).handleNewOccupation(train); + handleUnlocks(train); + return true; + } + + if( occupiedBy != null && occupiedBy != train) throw new RuntimeException("Two trains cannot be in same section! " + + train.toString() + " trying to enter section with " + occupiedBy.toString()); + + if(reservedBy == null || reservedBy != train) + throw new RuntimeException("Train should reserve section before trying to occupy it!"); + + occupiedBy = train; + handleUnlocks(train); + + JRidesPlugin.getLogger().info(LogType.SECTIONS,"Section " + this.toString() + " occupied by " + train); + return true; + } + + private void handleUnlocks(@NonNull Train train){ + if(arrivalUnlocks == null) return; + + CoasterHandle coasterHandle = train.getHandle().getCoasterHandle(); + Unlockable unlockable = coasterHandle.getUnlockable(arrivalUnlocks); + if(unlockable == null) + throw new RuntimeException("Trying to unlock " + arrivalUnlocks + " but it is unknown"); + + unlockable.unlock(train); + JRidesPlugin.getLogger().info(LogType.SECTIONS,"Unlock-able " + arrivalUnlocks + " unlocked by " + train); + } + + @Override + public void removeOccupation(@NonNull Train train) { + if(trackBehaviour.canHandleBlockSectionSafety()) { + ((SectionSafetyProvider)trackBehaviour).handleClearOccupation(train); + return; + } + + if(occupiedBy != train){ + String occupationString = occupiedBy != null ? occupiedBy.toString() : "null"; + throw new RuntimeException("Trying to remove train " + train + " from section " + this + " while occupation is different: " + occupationString); + } + + occupiedBy = null; + JRidesPlugin.getLogger().info(LogType.SECTIONS, "Section " + this.toString() + " has been exited"); + } + + @Override + public Section next(Train train) { + return next(train, false); + } + + @Override + public Section next(Train train, boolean processPassing) { + if(trackBehaviour.definesNextSection()){ + return trackBehaviour.getSectionNext(train, processPassing); + } + + return nextSection.acceptAsNext(train, processPassing); + } + + @Override + public Section previous(Train train) { + return previous(train, false); + } + + @Override + public Section previous(Train train, boolean processPassing) { + if(trackBehaviour.definesNextSection()){ + return trackBehaviour.getSectionPrevious(train, processPassing); + } + + return previousSection; + } + + @Override + public Collection
    allNextSections(Train train) { + if(trackBehaviour.definesNextSection()) + return trackBehaviour.getAllNextSections(train); + return List.of(next(train, false)); + } + + @Override + public Collection
    allPreviousSections(Train train) { + if(trackBehaviour.definesNextSection()) + return trackBehaviour.getAllPreviousSections(train); + return List.of(previous(train, false)); + } + + @Override + public Section acceptAsNext(Train train, boolean processPassing) { + if(trackBehaviour.definesNextAccepting()){ + return trackBehaviour.acceptAsNext(train, processPassing); + } + + return this; + } + + @Override + public boolean isNextSectionFor(Train train, Section section) { + return next(train) == section; + } + + @Override + public boolean isPreviousSectionFor(Train train, Section section) { + return previous(train) == section || additionalPreviousSections.contains(section); + } + + @Override + public void setNext(Section section) { + if(nextSection != null) throw new RuntimeException("Cannot set next section twice!"); + nextSection = section; + } + + @Override + public void setPrevious(Section section) { + if(previousSection != null){ +// throw new RuntimeException("Cannot set previous section twice! (Check if multiple sections point to the same singular section)"); + additionalPreviousSections.add(section); + return; + } + previousSection = section; + } + + @Override + public Track getParentTrack() { + return parentTrack; + } + + @Override + public void setParentTrack(Track track) { + if(parentTrack != null) + throw new RuntimeException("Section already has parent track"); + parentTrack = track; + getTrackBehaviour().setParentTrack(track); + } + + @Override + public String getName() { + return toString(); + } + + @Override + public boolean positiveDirectionToGoTo(Section section, Train forTrain) { + if(trackBehaviour.definesNextSection()){ + if(trackBehaviour.getSectionAtEnd(forTrain, false) == section) return true; + else if(trackBehaviour.getSectionAtStart(forTrain, false) == section) return false; + else throw new RuntimeException("Cannot determine behaviour-defined direction to go to section " + section + " for train " + forTrain); + }else{ + if(this.isNextSectionFor(forTrain, section)) return true; + else if(this.isPreviousSectionFor(forTrain, section)) return false; + else throw new RuntimeException("Cannot determine direction to go to section " + section + " for train " + forTrain); + } + } + + @Override + public boolean shouldJumpAtEnd() { + return false; + } + + @Override + public boolean shouldJumpAtStart() { + return false; + } + + @Override + public int compareTo(Section otherSection) { + if(this.getParentTrack().getIdentifier().compareTo(otherSection.getParentTrack().getIdentifier()) == 0) + return Integer.compare(getStartFrame().getValue(), otherSection.getStartFrame().getValue()); + return 0; + } + + @Override + public void setConflictSections(List
    sections) { + + } + + @Override + public boolean nextConnectsToStart() { + return true; + } + + @Override + public boolean previousConnectsToStart() { + return false; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/section/PointSection.java b/src/main/java/com/jverbruggen/jrides/models/ride/section/PointSection.java new file mode 100644 index 00000000..be08d212 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/section/PointSection.java @@ -0,0 +1,147 @@ +package com.jverbruggen.jrides.models.ride.section; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.TrackBehaviour; +import com.jverbruggen.jrides.logging.LogType; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.result.BlockSectionSafetyResult; + +import javax.annotation.Nullable; +import java.util.List; + +public class PointSection extends BaseSection { + private final Frame point; + private String name; + + public PointSection(TrackBehaviour trackBehaviour, Frame point, String name) { + super(trackBehaviour); + this.point = point; + this.name = name; + } + + @Override + public Frame getSpawnFrame() { + Frame behaviourDefinedSpawnFrame = trackBehaviour.getSpawnFrame(); + if(behaviourDefinedSpawnFrame == null) + return getEndFrame(); + return behaviourDefinedSpawnFrame; + } + + @Override + public Frame getStartFrame() { + return point; + } + + @Override + public Frame getEndFrame() { + return point; + } + + @Override + public boolean isInSection(Frame frame) { + return isInRawFrameRange(frame); + } + + @Override + public boolean isInRawFrameRange(Frame frame) { + return frame.getValue() == this.point.getValue(); + } + + @Override + public TrackBehaviour getTrackBehaviour() { + return trackBehaviour; + } + + @Override + public boolean canBlock() { + return false; + } + + @Override + public BlockSectionSafetyResult getBlockSectionSafety(@Nullable Train train, boolean checkConflicts) { + Section next = next(train); + if(next == null) return new BlockSectionSafetyResult(false, train, "No next section for train after point"); + return next.getBlockSectionSafety(train, true); + } + + @Override + public boolean canTrainSpawnOn() { + return trackBehaviour.canSpawnOn(); + } + + @Override + public boolean hasPassed(Frame staticFrame, Frame movingFrame) { + int staticFrameValue = staticFrame.getValue(); + int movingFrameValue = movingFrame.getValue(); + + return staticFrameValue <= movingFrameValue; + } + + @Override + public boolean hasPassedInverse(Frame staticFrame, Frame movingFrame) { + return hasPassed(movingFrame, staticFrame); + } + + @Override + public boolean passesCycle() { + return false; + } + + @Override + public boolean shouldJumpAtStart() { + return false; + } + + @Override + public boolean shouldJumpAtEnd() { + return false; + } + + @Override + public void setConflictSections(List
    sections) { + + } + + @Override + public boolean spansOver(Train train) { + Frame headOfTrainFrame = train.getHeadOfTrainFrame(); + Frame tailOfTrainFrame = train.getTailOfTrainFrame(); + JRidesPlugin.getLogger().info(LogType.SECTIONS, + "From " + this + " Spans over " + headOfTrainFrame.getValue() + " - " + tailOfTrainFrame.getValue()); + + Frame lowerFrame = train.isPositiveDrivingDirection() ? tailOfTrainFrame : headOfTrainFrame; + Frame upperFrame = train.isPositiveDrivingDirection() ? headOfTrainFrame : tailOfTrainFrame; + + return isInSection(headOfTrainFrame) + || isInSection(tailOfTrainFrame) + || Frame.isBetweenFrames(lowerFrame, upperFrame, point); + } + + @Override + public boolean isForwards() { + return true; + } + + @Override + public void setParentTrack(Track track) { + super.setParentTrack(track); + point.setTrack(track); + } + + @Override + public String toString() { + return ""; + } + + @Override + public String getName() { + if(name == null) return toString(); + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/section/Section.java b/src/main/java/com/jverbruggen/jrides/models/ride/section/Section.java new file mode 100644 index 00000000..85398c2b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/section/Section.java @@ -0,0 +1,91 @@ +package com.jverbruggen.jrides.models.ride.section; + +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.TrackBehaviour; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.result.BlockSectionSafetyResult; +import org.checkerframework.checker.nullness.qual.NonNull; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Collection; +import java.util.List; + +public interface Section extends Comparable
    { + Frame getSpawnFrame(); + Frame getStartFrame(); + Frame getEndFrame(); + boolean isInSection(Frame frame); + boolean isInRawFrameRange(Frame frame); + Track getParentTrack(); + void setParentTrack(Track track); + TrackBehaviour getTrackBehaviour(); + boolean isOccupied(); + boolean isOccupiedBy(Train train); + Train getOccupiedBy(); + boolean canHandleOccupation(Train train); + boolean canBlock(); + BlockSectionSafetyResult getBlockSectionSafety(@Nullable Train train); + BlockSectionSafetyResult getBlockSectionSafety(@Nullable Train train, boolean checkConflicts); + + void setLocalReservation(@Nonnull Train train); + void clearLocalReservation(@Nonnull Train authority); + boolean canReserveLocally(@Nullable Train train); + boolean canReserveEntireBlock(@Nonnull Train train); + void setEntireBlockReservation(@Nonnull Train train); + void clearEntireBlockReservation(@Nonnull Train authority); + void clearEntireBlockReservation(@Nonnull Train authority, List
    done); + @Nullable Train getReservedBy(); + boolean isReserved(); + boolean isReservedBy(Train train); + + boolean addOccupation(@NonNull Train train); + void removeOccupation(@NonNull Train train); + boolean canTrainSpawnOn(); + boolean hasPassed(Frame staticFrame, Frame movingFrame); + boolean hasPassedInverse(Frame staticFrame, Frame movingFrame); + boolean passesCycle(); + boolean shouldJumpAtStart(); + boolean shouldJumpAtEnd(); + + void setConflictSections(List
    sections); + + Vector3 getLocationFor(Frame frame); + Quaternion getOrientationFor(Frame frame); + + Section acceptAsNext(Train train, boolean processPassing); + + @Nullable + Section next(Train train); + @Nullable + Section next(Train train, boolean processPassing); + @Nullable + Section previous(Train train); + @Nullable + Section previous(Train train, boolean processPassing); + + Collection
    allNextSections(Train train); + Collection
    allPreviousSections(Train train); + + boolean isNextSectionFor(Train train, Section section); + boolean isPreviousSectionFor(Train train, Section section); + void setNext(Section section); + void setPrevious(Section section); + boolean spansOver(Train train); + boolean positiveDirectionToGoTo(Section section, Train forTrain); + + /** + * Is section forwards + * i.e. do trains traverse backwards or forwards through it? + * @return true if forwards + */ + boolean isForwards(); + + boolean nextConnectsToStart(); + boolean previousConnectsToStart(); + + String getName(); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/section/SectionSafetyProvider.java b/src/main/java/com/jverbruggen/jrides/models/ride/section/SectionSafetyProvider.java new file mode 100644 index 00000000..277e8d7d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/section/SectionSafetyProvider.java @@ -0,0 +1,19 @@ +package com.jverbruggen.jrides.models.ride.section; + +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.result.BlockSectionSafetyResult; + +import javax.annotation.Nonnull; + +public interface SectionSafetyProvider { + BlockSectionSafetyResult getEnteringSafety(Train train, Section nextSection); + boolean canHandleOccupation(@Nonnull Train train); + void handleNewReservation(@Nonnull Train train); + void handleClearReservation(@Nonnull Train train); + Train getReservation(); + void handleNewOccupation(@Nonnull Train train); + void handleClearOccupation(@Nonnull Train train); + boolean isReservedBy(@Nonnull Train train); + boolean isOccupied(); + boolean isOccupiedBy(@Nonnull Train train); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/section/SimpleSection.java b/src/main/java/com/jverbruggen/jrides/models/ride/section/SimpleSection.java new file mode 100644 index 00000000..ac9fc031 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/section/SimpleSection.java @@ -0,0 +1,212 @@ +package com.jverbruggen.jrides.models.ride.section; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.TrackBehaviour; +import com.jverbruggen.jrides.logging.LogType; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.result.BlockSectionSafetyResult; + +import javax.annotation.Nullable; +import java.util.List; + +public class SimpleSection extends BaseSection { + private final Frame startFrame; + private final Frame endFrame; + private final boolean jumpAtStart; + private final boolean jumpAtEnd; + private final boolean forwards; + private String name; + private List
    conflictSections; + + public SimpleSection(Frame startFrame, Frame endFrame, TrackBehaviour trackBehaviour, boolean jumpAtStart, boolean jumpAtEnd, boolean forwards) { + super(trackBehaviour); + this.startFrame = startFrame.clone(); + this.endFrame = endFrame.clone(); + this.jumpAtStart = jumpAtStart; + this.jumpAtEnd = jumpAtEnd; + this.forwards = forwards; + this.name = null; + this.conflictSections = null; + } + + @Override + public Frame getSpawnFrame() { + Frame behaviourDefinedSpawnFrame = trackBehaviour.getSpawnFrame(); + if(behaviourDefinedSpawnFrame == null) + return getEndFrame(); + return behaviourDefinedSpawnFrame; + } + + @Override + public Frame getStartFrame() { + return startFrame; + } + + @Override + public Frame getEndFrame() { + return endFrame; + } + + @Override + public boolean isInRawFrameRange(Frame frame) { + return Frame.isBetweenFrames(startFrame, endFrame, frame); + } + + @Override + public boolean isInSection(Frame frame) { + return parentTrack.equals(frame.getTrack()) && isInRawFrameRange(frame); + } + + @Override + public TrackBehaviour getTrackBehaviour() { + return trackBehaviour; + } + + @Override + public boolean canBlock() { + return trackBehaviour.canBlock(); + } + + @Override + public BlockSectionSafetyResult getBlockSectionSafety(@Nullable Train train, boolean checkConflicts) { + Section next = next(train); + + if(trackBehaviour.canHandleBlockSectionSafety()){ + return ((SectionSafetyProvider) trackBehaviour).getEnteringSafety(train, next); + } + + if(!this.canReserveLocally(train)){ + String reservedByString = getReservedBy() != null ? getReservedBy().getName() : "null"; + return new BlockSectionSafetyResult(false, train, "Cannot reserve locally, reserved by " + reservedByString); + } + if(train != null + && this.getOccupiedBy() != train + && this.getOccupiedBy() != null) return new BlockSectionSafetyResult(false, train, "Already occupied by " + this.getOccupiedBy()); + if(!this.trackBehaviour.accepts(train)) return new BlockSectionSafetyResult(false, train, "Track behaviour not ready for train"); + if(checkConflicts + && conflictSections != null + && conflictSections.stream().anyMatch(s -> !s.getBlockSectionSafety(train, false).safe())) + return new BlockSectionSafetyResult(false, train, "One of conflicting sections unsafe"); + + if(this.canBlock()) return new BlockSectionSafetyResult(true, train, "OK: Can block self"); + + if(next == null){ + throw new RuntimeException("Section was null for train when checking for block section safety"); + } + + if(!next.isPreviousSectionFor(train, this)) + return new BlockSectionSafetyResult(false, train, "Train and section order mismatch"); + + return next.getBlockSectionSafety(train); + } + + @Override + public boolean canTrainSpawnOn() { + return trackBehaviour.canSpawnOn(); + } + + @Override + public boolean hasPassed(Frame staticFrame, Frame movingFrame) { + int startFrameValue = startFrame.getValue(); + int endFrameValue = endFrame.getValue(); + int staticFrameValue = staticFrame.getValue(); + int movingFrameValue = movingFrame.getValue(); + + boolean normalPassed = startFrameValue < endFrameValue && staticFrameValue <= movingFrameValue; + boolean cyclicPassed = (startFrameValue > endFrameValue && ( + (staticFrameValue <= movingFrameValue && staticFrameValue >= startFrameValue) + || (staticFrameValue <= movingFrameValue && staticFrameValue <= endFrameValue && movingFrameValue <= endFrameValue) + || (staticFrameValue >= movingFrameValue && staticFrameValue >= startFrameValue && movingFrameValue <= endFrameValue) + )); + + return normalPassed || cyclicPassed; + } + + @Override + public boolean hasPassedInverse(Frame staticFrame, Frame movingFrame) { + return hasPassed(movingFrame, staticFrame); + } + + @Override + public boolean passesCycle() { + return startFrame.getValue() > endFrame.getValue(); + } + + @Override + public boolean shouldJumpAtStart() { + return jumpAtStart; + } + + @Override + public boolean shouldJumpAtEnd() { + return jumpAtEnd; + } + + @Override + public void setConflictSections(List
    sections) { + this.conflictSections = sections; + } + + @Override + public boolean spansOver(Train train) { + Frame headOfTrainFrame = train.getHeadOfTrainFrame(); + Frame tailOfTrainFrame = train.getTailOfTrainFrame(); + JRidesPlugin.getLogger().info(LogType.SECTIONS, + "From " + this + " Spans over " + headOfTrainFrame.getValue() + " - " + tailOfTrainFrame.getValue()); + + + Frame lowerFrame = train.isFacingForwards() ? tailOfTrainFrame : headOfTrainFrame; + Frame upperFrame = train.isFacingForwards() ? headOfTrainFrame : tailOfTrainFrame; + + return isInSection(headOfTrainFrame) + || isInSection(tailOfTrainFrame) + || Frame.isBetweenFrames(lowerFrame, upperFrame, endFrame) + || Frame.isBetweenFrames(lowerFrame, upperFrame, startFrame); + } + + @Override + public boolean isForwards() { + return forwards; + } + + @Override + public void setParentTrack(Track track) { + super.setParentTrack(track); + + startFrame.setTrack(track); + endFrame.setTrack(track); + } + + @Override + public String toString() { + return "<" + startFrame.getValueString() + "-" + endFrame.getValueString() + " " + trackBehaviour.getName() + " occ:" + isOccupied() + ">"; + } + + @Override + public String getName() { + if(name == null) return toString(); + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean previousConnectsToStart() { + if(trackBehaviour.canHandleConnections()){ + return trackBehaviour.previousConnectsToStart(); + } + return false; + } + + @Override + public boolean nextConnectsToStart() { + if(trackBehaviour.canHandleConnections()){ + return trackBehaviour.nextConnectsToStart(); + } + return true; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/section/Unlockable.java b/src/main/java/com/jverbruggen/jrides/models/ride/section/Unlockable.java new file mode 100644 index 00000000..c08e3864 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/section/Unlockable.java @@ -0,0 +1,7 @@ +package com.jverbruggen.jrides.models.ride.section; + +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +public interface Unlockable { + void unlock(Train authority); +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/section/builder/AdvancedSectionBuilder.java b/src/main/java/com/jverbruggen/jrides/models/ride/section/builder/AdvancedSectionBuilder.java new file mode 100644 index 00000000..8e5abf9b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/section/builder/AdvancedSectionBuilder.java @@ -0,0 +1,128 @@ +package com.jverbruggen.jrides.models.ride.section.builder; + +import com.jverbruggen.jrides.models.ride.coaster.transfer.Transfer; +import com.jverbruggen.jrides.models.ride.section.Section; +import com.jverbruggen.jrides.models.ride.section.reference.SectionReference; +import org.bukkit.Bukkit; + +import java.util.*; +import java.util.stream.Collectors; + +public class AdvancedSectionBuilder { + private final Map sectionReferences; + private boolean calculated; + private Map result; + + public AdvancedSectionBuilder() { + this.sectionReferences = new HashMap<>(); + this.calculated = false; + this.result = null; + } + + public AdvancedSectionBuilder add(SectionReference sectionReference){ + String sectionIdentifier = sectionReference.getSectionIdentifier(); + String nextSectionIdentifier = sectionReference.getNextSectionIdentifier(); + + if(sectionReferences.containsKey(nextSectionIdentifier)){ + SectionReference nextSectionReference = sectionReferences.get(nextSectionIdentifier); + nextSectionReference.setPreviousSectionIdentifier(sectionIdentifier); + } + + for(Map.Entry existingSection : sectionReferences.entrySet()){ + SectionReference existingSectionReference = existingSection.getValue(); + String existingNextSectionIdentifier = existingSectionReference.getNextSectionIdentifier(); + if(existingNextSectionIdentifier != null + && existingNextSectionIdentifier.equalsIgnoreCase(sectionIdentifier)){ + sectionReference.setPreviousSectionIdentifier(existingSectionReference.getSectionIdentifier()); + } + } + + sectionReferences.put(sectionIdentifier, sectionReference); + return this; + } + + private Map.Entry findSection(Map sections, String sectionIdentifier){ + if(sectionIdentifier == null) return null; + + Map.Entry found = null; + for(Map.Entry entry : sections.entrySet()){ + if(entry.getKey().getSectionIdentifier().equalsIgnoreCase(sectionIdentifier)){ + found = entry; + break; + } + } + if(found == null) + throw new RuntimeException("Section " + sectionIdentifier + " not found in map"); + + return found; + } + + public void calculate(){ + if(calculated) + throw new RuntimeException("Already calculated"); + + List allSectionReferences = new ArrayList<>(sectionReferences.values()); + + // --- Initialize section objects + Map sections = new HashMap<>(); + for(SectionReference sectionReference : allSectionReferences){ + sections.put(sectionReference, sectionReference.makeSection()); + } + + // --- Populate conflicting sections + for(Map.Entry entry : sections.entrySet()){ + SectionReference sectionReference = entry.getKey(); + Section section = entry.getValue(); + + List conflictSectionStrings = sectionReference.getConflictSectionStrings(); + if(conflictSectionStrings == null) continue; + + List
    conflictingSections = sections.values().stream() + .filter(s -> conflictSectionStrings.contains(s.getName())) + .collect(Collectors.toList()); + + section.setConflictSections(conflictingSections); +// conflictingSections.forEach(other -> Bukkit.broadcastMessage(section.getName() + " conflicts with " + other)); + } + + // --- Link section ends together + for(Map.Entry entry : sections.entrySet()){ + SectionReference sectionReference = entry.getKey(); + Section section = entry.getValue(); + + Map.Entry foundNextSectionEntry = findSection(sections, sectionReference.getNextSectionIdentifier()); + Section nextSection = null; + if(foundNextSectionEntry != null) + nextSection = foundNextSectionEntry.getValue(); + + section.setNext(nextSection); + if(nextSection != null) + nextSection.setPrevious(section); + } + + this.result = sections; + this.calculated = true; + } + + public void populateTransfers(List transfers){ + for(Transfer transfer : transfers){ + transfer.populateTransferPositionSections(result); + } + } + + public void populateBehaviours(){ + for(Section section : result.values()){ + section.getTrackBehaviour().populateSectionReferences(result); + } + } + + public List
    collectFor(String track){ + if(!this.calculated) throw new RuntimeException("Calculate the builder before collecting"); + + return result.entrySet().stream() + .filter(entry -> entry.getKey().getParentTrackIdentifier().equalsIgnoreCase(track)) + .map(Map.Entry::getValue) + .collect(Collectors.toList()); + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/section/builder/SectionBuilder.java b/src/main/java/com/jverbruggen/jrides/models/ride/section/builder/SectionBuilder.java new file mode 100644 index 00000000..3f5c3209 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/section/builder/SectionBuilder.java @@ -0,0 +1,61 @@ +package com.jverbruggen.jrides.models.ride.section.builder; + +import com.jverbruggen.jrides.models.ride.section.Section; + +import java.util.ArrayList; +import java.util.List; + +public class SectionBuilder { + private final List
    sections; + private boolean collected; + private final boolean tieLooseEnds; + + public SectionBuilder(boolean tieLooseEnds) { + this.sections = new ArrayList<>(); + this.collected = false; + this.tieLooseEnds = tieLooseEnds; + } + + private Section getFirstItem(){ + if(sections.size() == 0) return null; + return sections.get(0); + } + + private Section getLastItem(){ + if(sections.size() == 0) return null; + return sections.get(sections.size()-1); + } + + public SectionBuilder add(Section section){ + Section previousSection = getLastItem(); + if(previousSection != null){ + section.setPrevious(previousSection); + previousSection.setNext(section); + } + + sections.add(section); + return this; + } + + public List
    collect(){ + if(sections.size() == 0) throw new RuntimeException("Cannot collect empty section builder"); + if(collected) throw new RuntimeException("Builder was already collected"); + collected = true; + + if(tieLooseEnds){ + Section firstSection = getFirstItem(); + Section lastSection = getLastItem(); + + assert firstSection != null; + assert lastSection != null; + + firstSection.setPrevious(lastSection); + lastSection.setNext(firstSection); + } + + return sections; + } + + + +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/section/exception/SectionNotFoundException.java b/src/main/java/com/jverbruggen/jrides/models/ride/section/exception/SectionNotFoundException.java new file mode 100644 index 00000000..2d7c8fa0 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/section/exception/SectionNotFoundException.java @@ -0,0 +1,16 @@ +package com.jverbruggen.jrides.models.ride.section.exception; + +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +public class SectionNotFoundException extends RuntimeException { + private final Train train; + + public SectionNotFoundException(Train train) { + this.train = train; + } + + @Override + public String getMessage() { + return "Section not found for train " + this.train.toString(); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/section/provider/SectionProvider.java b/src/main/java/com/jverbruggen/jrides/models/ride/section/provider/SectionProvider.java new file mode 100644 index 00000000..c269ac9d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/section/provider/SectionProvider.java @@ -0,0 +1,320 @@ +package com.jverbruggen.jrides.models.ride.section.provider; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.logging.JRidesLogger; +import com.jverbruggen.jrides.logging.LogType; +import com.jverbruggen.jrides.models.properties.Speed; +import com.jverbruggen.jrides.models.properties.TrainEnd; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.frame.SimpleFrame; +import com.jverbruggen.jrides.models.properties.TrackEnd; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.CoasterCart; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.Section; +import com.jverbruggen.jrides.models.ride.section.exception.SectionNotFoundException; +import org.checkerframework.checker.nullness.qual.NonNull; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BiFunction; + +public class SectionProvider { + public void addFramesWithSectionLogic(TrainHandle trainHandle, Frame toFrame, int value){ + addFramesWithSectionLogic(trainHandle, toFrame, value, false, null, "", false); + } + + public void addFramesWithSectionLogic(TrainHandle trainHandle, Frame toFrame, int value, boolean updateSectionOccupations, TrainEnd trainEnd, String debugName, boolean applyNewBehaviour){ + Frame fromFrame = toFrame.capture(); + toFrame.setValue(value); + + Section fromSection = fromFrame.getSection(); + if(fromSection.isInSection(toFrame)) return; + + Train train = trainHandle.getTrain(); + boolean positiveDrivingDirection = train.isPositiveDrivingDirection(); + Section toNewSection = getSectionFor(train, fromSection, fromFrame, toFrame, applyNewBehaviour); + + if(updateSectionOccupations){ + JRidesPlugin.getLogger().info(LogType.SECTIONS, debugName + ": " + trainEnd + "(" + positiveDrivingDirection); + JRidesPlugin.getLogger().info(LogType.SECTIONS, "to " + debugName + ": " + fromSection + " => " + toNewSection); + sectionOccupationLogic(trainHandle, fromSection, toNewSection, trainEnd, applyNewBehaviour); + } + + toFrame.setSection(toNewSection); + toFrame.setInvertedFrameAddition(!train.isFacingForwards()); + } + + private void clearSectionOccupation(Train train, Section section){ + section.removeOccupation(train); + train.removeCurrentSection(section); + + if(section.canBlock()) section.clearEntireBlockReservation(train); + section.getTrackBehaviour().trainExitedAtEnd(train, section); + } + + private void checkFlushRemainingSections(Train train, Section toSection){ + List
    currentSections = List.copyOf(train.getCurrentSections()); + if(currentSections.size() > 1){ + for(Section currentSection : currentSections){ + if(currentSection == toSection) continue; + if(!currentSection.spansOver(train)){ + clearSectionOccupation(train, currentSection); + JRidesPlugin.getLogger().info(LogType.SECTIONS, "sectionLogic - Cleared remaining section " + currentSection.getName()); + } + } + } + } + + public void sectionOccupationLogic(TrainHandle trainHandle, Section fromSection, Section toSection, TrainEnd onTrainEnd, boolean applyNewBehaviour){ + final Train train = trainHandle.getTrain(); + + // If the section it is entering is occupied by some train + if(toSection.isOccupiedBy(train)){ + JRidesPlugin.getLogger().info(LogType.SECTIONS, "sectionLogic - Occupied"); + if(applyNewBehaviour) trainHandle.setTrackBehaviour(toSection.getTrackBehaviour()); + if(!fromSection.spansOver(train)){ + JRidesPlugin.getLogger().info(LogType.SECTIONS, "sectionLogic - Not spans over"); + clearSectionOccupation(train, fromSection); + + checkFlushRemainingSections(train, toSection); + }else{ + JRidesPlugin.getLogger().info(LogType.SECTIONS, "sectionLogic - Yes spans over"); + } + }else if(toSection.isOccupied() && !toSection.canHandleOccupation(train)){ + // If that train is a different train, crash + train.setCrashed(true); + sendTrainCrashMessage(train, toSection, null); + // else if that train is self + }else{ + // else if the section is free, occupy it + if(!toSection.isReservedBy(train)){ + if(!toSection.getBlockSectionSafety(train).safe()) + throw new RuntimeException("Logic error: Section " + toSection.getName() + " was not reserved in section occupation logic!"); + toSection.setLocalReservation(train); + } + + toSection.addOccupation(train); + train.addCurrentSection(toSection, onTrainEnd); + if(applyNewBehaviour){ + trainHandle.setTrackBehaviour(toSection.getTrackBehaviour()); + + train.setDrivingDirection(true); // Default to true +// if(fromSection.next(train, false) == toSection) +// train.setDrivingDirection(true); +// else if(fromSection.previous(train, false) == toSection) +// train.setDrivingDirection(false); +// else +// train.setDrivingDirection(true); // Default to true + } + } + } + + private void sendTrainCrashMessage(Train train, Section onSection, Frame onFrame) { + JRidesLogger logger = JRidesPlugin.getLogger(); + logger.warning(LogType.CRASH, "Train " + train + " has crashed!"); + logger.warning(LogType.CRASH, "| head-fr: " + train.getHeadOfTrainFrame()); + logger.warning(LogType.CRASH, "| midl-fr: " + train.getMiddleOfTrainFrame()); + logger.warning(LogType.CRASH, "| tail-fr: " + train.getTailOfTrainFrame()); + logger.warning(LogType.CRASH, "| head-sc: " + train.getHeadSection()); + logger.warning(LogType.CRASH, "| tail-sc: " + train.getTailSection()); + logger.warning(LogType.CRASH, "crash-sc:" + onSection.toString()); + logger.warning(LogType.CRASH, "crash-fr:" + onFrame); + for(CoasterCart cart : train.getCarts()){ + logger.warning(LogType.CRASH, "| cart-fr: " + cart.getFrame()); + } + } + + public @NonNull Section getSectionFor(Train train, Section fromSection, Frame fromFrame, Frame toFrame, boolean canProcess){ + if(fromSection.isInSection(toFrame)) return fromSection; + + if(fromFrame.getTrack() != toFrame.getTrack()){ + return getSectionOnDifferentTrack(train, fromSection, toFrame, canProcess); + } + + final Section subsequentNextSection = fromSection.next(train, canProcess); + final Section subsequentPreviousSection = fromSection.previous(train); + if(subsequentNextSection != null){ + Section result = processNextSection(subsequentNextSection, train, fromSection, fromFrame, toFrame, false); + if(result != null) return result; + }else if(subsequentPreviousSection != null){ + Section result = processPreviousSection(subsequentPreviousSection, train, fromSection, fromFrame, toFrame); + if(result != null) return result; + } + + Speed speed = train.getHandle().getSpeed(); + boolean isDrivingForwards = speed.isGoingForwards(); + final BiFunction relativeFunction = isDrivingForwards + ? Section::next + : Section::previous; + Section found = findSectionBySearchingRelative(train, toFrame, fromSection, relativeFunction); + +// if(found == null){ +// Collection
    neighbors = fromSection.allPreviousSections(train); +// Bukkit.broadcastMessage("Checking"); +// for(Section neighbor : neighbors){ +// Bukkit.broadcastMessage("Checking: " + neighbor); +// if(neighbor.isInSection(toFrame)){ +// JRidesPlugin.getLogger().info(LogType.SECTIONS,"Found section in neighbors"); +// Section result = processNextSection(neighbor, train, fromSection, fromFrame, toFrame, true); +// if(result != null) return result; +// } +// } +// } + + if(found == null){ + train.setCrashed(true); + JRidesPlugin.getLogger().info(LogType.CRASH, + "Section not found!: " + fromSection + " from " + fromFrame + " to: " + toFrame); + sendTrainCrashMessage(train, fromSection, fromFrame); + throw new SectionNotFoundException(train); + }else{ + JRidesPlugin.getLogger().info(LogType.SECTIONS, + "Section found when searched!"); + } + + return found; + } + + private Section processNextSection(Section subsequentNextSection, Train train, Section fromSection, Frame fromFrame, Frame toFrame, boolean forceJump){ + if(subsequentNextSection.isInSection(toFrame) && !forceJump) { + JRidesPlugin.getLogger().info(LogType.SECTIONS, "isnext!"); + return subsequentNextSection; + } else if((fromSection.isInSection(fromFrame) && train.getDirection() == TrackEnd.END) + || fromSection.shouldJumpAtEnd()){ + int overshotFrameAmount = getOvershotFrameAmount(train, fromSection, fromFrame, toFrame); + int newFrameValue; + Frame nextAttachedFrame; + if(fromSection.nextConnectsToStart()){ + nextAttachedFrame = subsequentNextSection.getStartFrame(); + newFrameValue = nextAttachedFrame.getValue() + overshotFrameAmount; + }else{ + nextAttachedFrame = subsequentNextSection.getEndFrame(); + newFrameValue = nextAttachedFrame.getValue() - overshotFrameAmount; + } + + JRidesPlugin.getLogger().info(LogType.SECTIONS, + "isnext! jumping - to: " + toFrame.getValue() + " over: " + overshotFrameAmount + ", new: " + newFrameValue); + + toFrame.updateTo(new SimpleFrame(newFrameValue, nextAttachedFrame.getTrack(), nextAttachedFrame.getSection())); + return subsequentNextSection; + } + return null; + } + + private Section processPreviousSection(Section subsequentPreviousSection, Train train, Section fromSection, Frame fromFrame, Frame toFrame){ + if(subsequentPreviousSection.isInSection(toFrame)){ + JRidesPlugin.getLogger().info(LogType.SECTIONS, "isprev!"); + return subsequentPreviousSection; + } else if((fromSection.isInSection(fromFrame) && train.getDirection() == TrackEnd.START) + || fromSection.shouldJumpAtStart()){ + int overshotFrameAmount = getOvershotFrameAmount(train, fromSection, fromFrame, toFrame); + int newFrameValue; + Frame previousAttachedFrame; + if(fromSection.previousConnectsToStart()){ + previousAttachedFrame = subsequentPreviousSection.getStartFrame(); + newFrameValue = previousAttachedFrame.getValue() - overshotFrameAmount; + }else{ + previousAttachedFrame = subsequentPreviousSection.getEndFrame(); + newFrameValue = previousAttachedFrame.getValue() + overshotFrameAmount; + } + + JRidesPlugin.getLogger().info(LogType.SECTIONS, + "isprev! jumping - to: " + toFrame.getValue() + " over: " + overshotFrameAmount + ", new: " + newFrameValue); + + toFrame.updateTo(new SimpleFrame(newFrameValue, previousAttachedFrame.getTrack(), previousAttachedFrame.getSection())); + return subsequentPreviousSection; + } + JRidesPlugin.getLogger().info(LogType.SECTIONS, "isprev none!"); + return null; + } + + private int getOvershotFrameAmount(Train train, Section currentSection, Frame fromFrame, Frame toFrame){ + Speed speed = train.getHandle().getSpeed(); + boolean isDrivingForwards = speed.isGoingForwards(); + + if(isDrivingForwards) { + if(toFrame.isInvertedFrameAddition()){ + JRidesPlugin.getLogger().info(LogType.SECTIONS, "overshot F I"); +// return currentSection.getEndFrame().getValue() - toFrame.getValue(); + return toFrame.getValue() - currentSection.getStartFrame().getValue(); + }else{ + JRidesPlugin.getLogger().info(LogType.SECTIONS, "overshot F NI (untested)"); + return toFrame.getValue() - currentSection.getEndFrame().getValue(); + } + }else{ + if(toFrame.isInvertedFrameAddition()){ + JRidesPlugin.getLogger().info(LogType.SECTIONS, "overshot B I (untested)"); +// return currentSection.getStartFrame().getValue() - toFrame.getValue(); + return toFrame.getValue() - currentSection.getEndFrame().getValue(); + }else{ + JRidesPlugin.getLogger().info(LogType.SECTIONS, "overshot B NI"); + return toFrame.getValue() - currentSection.getStartFrame().getValue(); + } + } + } + + public Section findSectionBySearchingNext(Train train, Frame frame, Section firstSection) { + return findSectionBySearchingRelative(train, frame, firstSection, Section::next); + } + + public Section findSectionBySearchingPrevious(Train train, Frame frame, Section firstSection) { + return findSectionBySearchingRelative(train, frame, firstSection, Section::previous); + } + + private Section findSectionBySearchingRelative(Train train, Frame frame, Section firstSection, BiFunction relativeFunction){ + List
    checked = new ArrayList<>(); + + Section found = null; + Section checking = firstSection; + while(checking != null && found == null){ + if(checking.isInSection(frame)){ + found = checking; + }else{ + checked.add(checking); + checking = relativeFunction.apply(checking, train); + + if(checked.contains(checking)) + checking = null; + } + } + + return found; + } + + public Section findSectionInBulk(Frame frame, List
    sections){ + Section found = null; + int i = 0; + while(found == null && i < sections.size()){ + Section compare = sections.get(i); + + if(compare.isInRawFrameRange(frame)) found = compare; + + i++; + } + + return found; + } + + public Section getSectionOnDifferentTrack(Train train, Section currentSection, Frame toFrame, boolean canProcess){ + Track newTrack = toFrame.getTrack(); + List
    newTrackSections = newTrack.getSections(); + + // If rolling forwards + Section logicalNextSection = currentSection.next(train, canProcess); + Section firstSectionNewTrack = newTrackSections.get(0); + if(logicalNextSection.equals(firstSectionNewTrack)){ + return logicalNextSection; + } + + // If rolling backwards + Section logicalPreviousSection = currentSection.previous(train); + Section lastSectionNewTrack = newTrackSections.get(newTrackSections.size()-1); + if(logicalPreviousSection.equals(lastSectionNewTrack)){ + return logicalPreviousSection; + } + + throw new RuntimeException("Unknown situation to handle section on different track"); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/section/reference/PointSectionReference.java b/src/main/java/com/jverbruggen/jrides/models/ride/section/reference/PointSectionReference.java new file mode 100644 index 00000000..79d4ed3d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/section/reference/PointSectionReference.java @@ -0,0 +1,66 @@ +package com.jverbruggen.jrides.models.ride.section.reference; + +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.TrackBehaviour; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.section.PointSection; +import com.jverbruggen.jrides.models.ride.section.Section; + +import java.util.List; + +public class PointSectionReference extends SectionReference { + private final String sectionIdentifier; + private final String nextSectionIdentifier; + private String previousSectionIdentifier; + private final String parentTrackIdentifier; + private final Frame point; + private final TrackBehaviour trackBehaviour; + + public PointSectionReference(String sectionIdentifier, Frame point, TrackBehaviour trackBehaviour, String nextSectionIdentifier, + String parentTrackIdentifier) { + this.sectionIdentifier = sectionIdentifier; + this.point = point; + this.trackBehaviour = trackBehaviour; + this.nextSectionIdentifier = nextSectionIdentifier; + this.previousSectionIdentifier = null; + this.parentTrackIdentifier = parentTrackIdentifier; + } + + @Override + public void setPreviousSectionIdentifier(String previousSectionIdentifier) { + this.previousSectionIdentifier = previousSectionIdentifier; + } + + @Override + public String getPreviousSectionIdentifier() { + return previousSectionIdentifier; + } + + @Override + public String getSectionIdentifier() { + return sectionIdentifier; + } + + public TrackBehaviour getTrackBehaviour() { + return trackBehaviour; + } + + @Override + public String getNextSectionIdentifier() { + return nextSectionIdentifier; + } + + @Override + public String getParentTrackIdentifier() { + return parentTrackIdentifier; + } + + @Override + public Section makeSection() { + return new PointSection(trackBehaviour, point, sectionIdentifier); + } + + @Override + public List getConflictSectionStrings() { + return null; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/section/reference/RangedSectionReference.java b/src/main/java/com/jverbruggen/jrides/models/ride/section/reference/RangedSectionReference.java new file mode 100644 index 00000000..33441086 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/section/reference/RangedSectionReference.java @@ -0,0 +1,114 @@ +package com.jverbruggen.jrides.models.ride.section.reference; + +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.TrackBehaviour; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.section.Section; +import com.jverbruggen.jrides.models.ride.section.SimpleSection; + +import java.util.List; + +public class RangedSectionReference extends SectionReference { + private final String sectionIdentifier; + private final String nextSectionIdentifier; + private String previousSectionIdentifier; + private final String parentTrackIdentifier; + private final String arrivalUnlocks; + private final Frame startFrame; + private final Frame endFrame; + private final TrackBehaviour trackBehaviour; + private final boolean jumpAtStart; + private final boolean jumpAtEnd; + private final boolean forwards; + + private final List conflictSectionsStrings; + + public RangedSectionReference(String sectionIdentifier, Frame startFrame, Frame endFrame, TrackBehaviour trackBehaviour, String nextSectionIdentifier, + List conflictSections, String parentTrackIdentifier, String arrivalUnlocks, boolean jumpAtStart, boolean jumpAtEnd, boolean forwards) { + this.sectionIdentifier = sectionIdentifier; + this.startFrame = startFrame; + this.endFrame = endFrame; + this.trackBehaviour = trackBehaviour; + this.nextSectionIdentifier = nextSectionIdentifier; + this.conflictSectionsStrings = conflictSections; + this.arrivalUnlocks = arrivalUnlocks; + this.jumpAtStart = jumpAtStart; + this.jumpAtEnd = jumpAtEnd; + this.forwards = forwards; + this.previousSectionIdentifier = null; + this.parentTrackIdentifier = parentTrackIdentifier; + } + + @Override + public void setPreviousSectionIdentifier(String previousSectionIdentifier) { + this.previousSectionIdentifier = previousSectionIdentifier; + } + + @Override + public String getPreviousSectionIdentifier() { + return previousSectionIdentifier; + } + + @Override + public String getSectionIdentifier() { + return sectionIdentifier; + } + + public String getArrivalUnlocks() { + return arrivalUnlocks; + } + + public Frame getStartFrame() { + return startFrame; + } + + public Frame getEndFrame() { + return endFrame; + } + + public TrackBehaviour getTrackBehaviour() { + return trackBehaviour; + } + + @Override + public String getNextSectionIdentifier() { + return nextSectionIdentifier; + } + + @Override + public String getParentTrackIdentifier() { + return parentTrackIdentifier; + } + + @Override + public Section makeSection() { + Frame startFrame = getStartFrame(); + Frame endFrame = getEndFrame(); + TrackBehaviour trackBehaviour = getTrackBehaviour(); + boolean jumpAtStart = isJumpAtStart(); + boolean jumpAtEnd = isJumpAtEnd(); + boolean forwards = isForwards(); + + SimpleSection section = new SimpleSection(startFrame, endFrame, trackBehaviour, jumpAtStart, jumpAtEnd, forwards); + section.setName(getSectionIdentifier()); + section.setArrivalUnlocks(arrivalUnlocks); + return section; + } + + @Override + public List getConflictSectionStrings() { + return conflictSectionsStrings; + } + + public boolean isJumpAtEnd() { + return jumpAtEnd; + } + + public boolean isJumpAtStart() { + return jumpAtStart; + } + + public boolean isForwards() { + return forwards; + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/section/reference/SectionReference.java b/src/main/java/com/jverbruggen/jrides/models/ride/section/reference/SectionReference.java new file mode 100644 index 00000000..c6c26c83 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/section/reference/SectionReference.java @@ -0,0 +1,34 @@ +package com.jverbruggen.jrides.models.ride.section.reference; + +import com.jverbruggen.jrides.models.ride.section.Section; + +import java.util.List; +import java.util.Map; + +public abstract class SectionReference { + public static Section findByIdentifier(String sectionIdentifier, Map sectionMap){ + return sectionMap.entrySet() + .stream() + .filter(entry -> entry.getKey().getSectionIdentifier().equalsIgnoreCase(sectionIdentifier)) + .findFirst().orElseThrow().getValue(); + } + + public abstract void setPreviousSectionIdentifier(String previousSectionIdentifier); + + public abstract String getPreviousSectionIdentifier(); + + public abstract String getSectionIdentifier(); + + public abstract String getNextSectionIdentifier(); + + public abstract String getParentTrackIdentifier(); + + public abstract Section makeSection(); + + public abstract List getConflictSectionStrings(); + + @Override + public String toString() { + return ""; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/section/result/BlockSectionSafetyResult.java b/src/main/java/com/jverbruggen/jrides/models/ride/section/result/BlockSectionSafetyResult.java new file mode 100644 index 00000000..013d84dc --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/section/result/BlockSectionSafetyResult.java @@ -0,0 +1,24 @@ +package com.jverbruggen.jrides.models.ride.section.result; + +import com.jverbruggen.jrides.models.ride.coaster.train.Train; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +public record BlockSectionSafetyResult(boolean safe, @Nullable Train forTrain, @Nonnull String reason) { + public static BlockSectionSafetyResult emptyFalse(){ + return new BlockSectionSafetyResult(false, null, ""); + } + + @Override + public String reason() { + String trainName = forTrain != null ? forTrain.getName() : "null"; + String sections = forTrain != null ? String.join(",", forTrain.getCurrentSections().stream().map(Object::toString).toList()) : "null"; + return "(" + trainName + ") [" + sections + "] " + reason; + } + + @Override + public String toString() { + return reason(); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/section/transfer/StraightTransferSection.java b/src/main/java/com/jverbruggen/jrides/models/ride/section/transfer/StraightTransferSection.java new file mode 100644 index 00000000..4cacf7a8 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/section/transfer/StraightTransferSection.java @@ -0,0 +1,90 @@ +package com.jverbruggen.jrides.models.ride.section.transfer; + +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.TrackBehaviour; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.section.BaseSection; +import com.jverbruggen.jrides.models.ride.section.result.BlockSectionSafetyResult; + +public class StraightTransferSection extends BaseSection { + public TransferPosition currentTransferPosition; + public Track transferTrack; + + private Frame transferStartFrame; + private Frame transferEndFrame; + + public StraightTransferSection() { + super(null); + } + + @Override + public Frame getSpawnFrame() { + return getEndFrame(); + } + + @Override + public Frame getStartFrame() { + return transferStartFrame; + } + + @Override + public Frame getEndFrame() { + return transferEndFrame; + } + + @Override + public boolean isInSection(Frame frame) { + return false; + } + + @Override + public boolean isInRawFrameRange(Frame frame) { + return false; + } + + @Override + public TrackBehaviour getTrackBehaviour() { + return null; + } + + @Override + public boolean canBlock() { + return false; + } + + @Override + public BlockSectionSafetyResult getBlockSectionSafety(Train train, boolean checkConflicts) { + return BlockSectionSafetyResult.emptyFalse(); + } + + @Override + public boolean canTrainSpawnOn() { + return false; + } + + @Override + public boolean hasPassed(Frame staticFrame, Frame movingFrame) { + return false; + } + + @Override + public boolean hasPassedInverse(Frame staticFrame, Frame movingFrame) { + return false; + } + + @Override + public boolean passesCycle() { + return false; + } + + @Override + public boolean spansOver(Train train) { + return false; + } + + @Override + public boolean isForwards() { + return true; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/section/transfer/TransferPosition.java b/src/main/java/com/jverbruggen/jrides/models/ride/section/transfer/TransferPosition.java new file mode 100644 index 00000000..306b2d31 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/section/transfer/TransferPosition.java @@ -0,0 +1,31 @@ +package com.jverbruggen.jrides.models.ride.section.transfer; + +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.properties.frame.Frame; + +public class TransferPosition { + private Frame connectionAtStart; + private Frame connectionAtEnd; + + private Vector3 transferPosition; + private Quaternion transferRotation; + + + public boolean canExitAtStart(){ + return connectionAtStart != null; + } + + public boolean canExitAtEnd(){ + return connectionAtEnd != null; + } + + public Quaternion getTransferRotation() { + return transferRotation; + } + + public Vector3 getTransferPosition() { + return transferPosition; + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/models/ride/state/OpenState.java b/src/main/java/com/jverbruggen/jrides/models/ride/state/OpenState.java new file mode 100644 index 00000000..13fd6c18 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/models/ride/state/OpenState.java @@ -0,0 +1,323 @@ +package com.jverbruggen.jrides.models.ride.state; + +import com.jverbruggen.jrides.animator.RideHandle; + +public enum OpenState { + /** + * Open state + */ + OPEN{ + @Override + public boolean isOpen() { + return true; + } + + @Override + public boolean isOpening() { + return false; + } + + @Override + public boolean isClosing() { + return false; + } + + @Override + public OpenState open(RideHandle rideHandle) { + return this; + } + + @Override + public OpenState close(RideHandle rideHandle) { + rideHandle.broadcastRideClose(); + + return TRANSITION_TO_CLOSE; + } + + @Override + public boolean canUnload() { + return false; + } + + @Override + public OpenState getSaveState() { + return this; + } + }, + /** + * Closed state + */ + CLOSED { + @Override + public boolean isOpen() { + return false; + } + + @Override + public boolean isOpening() { + return false; + } + + @Override + public boolean isClosing() { + return false; + } + + @Override + public OpenState open(RideHandle rideHandle) { + rideHandle.broadcastRideOpen(); + return OPEN; + } + + @Override + public OpenState close(RideHandle rideHandle) { + return this; + } + + @Override + public boolean canUnload() { + return true; + } + + @Override + public OpenState getSaveState() { + return this; + } + }, + /** + * Maintenance state, ride is loaded but not available to the public. It does appear in the ride overview menu + */ + MAINTENANCE { + @Override + public boolean isOpen() { + return false; + } + + @Override + public boolean isOpening() { + return false; + } + + @Override + public boolean isClosing() { + return false; + } + + @Override + public OpenState open(RideHandle rideHandle) { + return this; + } + + @Override + public OpenState close(RideHandle rideHandle) { + return this; + } + + @Override + public boolean canUnload() { + return true; + } + + @Override + public OpenState getSaveState() { + return this; + } + }, + /** + * Hidden state, ride is loaded but not available to the public. It does not appear in the ride overview menu + */ + HIDDEN { + @Override + public boolean isOpen() { + return false; + } + + @Override + public boolean isOpening() { + return false; + } + + @Override + public boolean isClosing() { + return false; + } + + @Override + public OpenState open(RideHandle rideHandle) { + return this; + } + + @Override + public OpenState close(RideHandle rideHandle) { + return this; + } + + @Override + public boolean canUnload() { + return true; + } + + @Override + public OpenState getSaveState() { + return this; + } + }, + /** + * Disabled state, the ride is not loaded at all + */ + DISABLED { + @Override + public boolean isOpen() { + return false; + } + + @Override + public boolean isOpening() { + return false; + } + + @Override + public boolean isClosing() { + return false; + } + + @Override + public OpenState open(RideHandle rideHandle) { + return this; + } + + @Override + public OpenState close(RideHandle rideHandle) { + return this; + } + + @Override + public boolean canUnload() { + return true; + } + + @Override + public OpenState getSaveState() { + return this; + } + }, + /** + * Inactive state, ride is partially loaded. Track and trains are not loaded. Does appear in the ride overview menu + */ + INACTIVE{ + @Override + public boolean isOpen() { + return false; + } + + @Override + public boolean isOpening() { + return false; + } + + @Override + public boolean isClosing() { + return false; + } + + @Override + public OpenState open(RideHandle rideHandle) { + return this; + } + + @Override + public OpenState close(RideHandle rideHandle) { + return this; + } + + @Override + public boolean canUnload() { + return true; + } + + @Override + public OpenState getSaveState() { + return this; + } + }, + TRANSITION_TO_CLOSE { + @Override + public boolean isOpen() { + return false; + } + + @Override + public boolean isOpening() { + return false; + } + + @Override + public boolean isClosing() { + return true; + } + + @Override + public OpenState open(RideHandle rideHandle) { + return this; + } + + @Override + public OpenState close(RideHandle rideHandle) { + return this; + } + + @Override + public boolean canUnload() { + return false; + } + + @Override + public OpenState getSaveState() { + return CLOSED; + } + }, + TRANSITION_TO_OPEN { + @Override + public boolean isOpen() { + return false; + } + + @Override + public boolean isOpening() { + return true; + } + + @Override + public boolean isClosing() { + return false; + } + + @Override + public OpenState open(RideHandle rideHandle) { + return this; + } + + @Override + public OpenState close(RideHandle rideHandle) { + return this; + } + + @Override + public boolean canUnload() { + return false; + } + + @Override + public OpenState getSaveState() { + return OPEN; + } + }; + + public abstract boolean isOpen(); + public abstract boolean isOpening(); + public abstract boolean isClosing(); + public abstract OpenState open(RideHandle rideHandle); + public abstract OpenState close(RideHandle rideHandle); + public abstract boolean canUnload(); + public abstract OpenState getSaveState(); +} diff --git a/src/main/java/com/jverbruggen/jrides/nms/NMSHandler.java b/src/main/java/com/jverbruggen/jrides/nms/NMSHandler.java new file mode 100644 index 00000000..2987b24f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/nms/NMSHandler.java @@ -0,0 +1,8 @@ +package com.jverbruggen.jrides.nms; + +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.math.Vector3; + +public interface NMSHandler { + void setPlayerLocationNoTeleport(Player player, Vector3 position); +} diff --git a/src/main/java/com/jverbruggen/jrides/nms/NMSHandlerFactory.java b/src/main/java/com/jverbruggen/jrides/nms/NMSHandlerFactory.java new file mode 100644 index 00000000..b81cafd0 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/nms/NMSHandlerFactory.java @@ -0,0 +1,17 @@ +package com.jverbruggen.jrides.nms; + +import org.bukkit.Bukkit; + +public class NMSHandlerFactory { + public static NMSHandler getNMSHandler(){ + String currentVersion = Bukkit.getVersion(); + + if(currentVersion.contains("1.19.2")){ + return new NMSHandler_1_19_2(); + }else if(currentVersion.contains("1.20")){ + return new NMSHandler_1_19_2(); + } + + throw new RuntimeException("No nms handler implemented for bukkit version '" + currentVersion + "'"); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/nms/NMSHandler_1_19_2.java b/src/main/java/com/jverbruggen/jrides/nms/NMSHandler_1_19_2.java new file mode 100644 index 00000000..b77d3986 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/nms/NMSHandler_1_19_2.java @@ -0,0 +1,58 @@ +package com.jverbruggen.jrides.nms; + +import com.comphenix.protocol.utility.MinecraftReflection; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.math.Vector3; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public class NMSHandler_1_19_2 implements NMSHandler { + + /** + * Same as: + * ((CraftPlayer) player.getBukkitPlayer()).getHandle().setPos(0,0,0); + * But should work across multiple versions + * @param player + * @param position + */ + @Override + public void setPlayerLocationNoTeleport(Player player, Vector3 position) { + org.bukkit.entity.Player bukkitPlayer = player.getBukkitPlayer(); + double x = position.getX(); + double y = position.getY(); + double z = position.getZ(); + + Class craftPlayerClass = MinecraftReflection.getCraftPlayerClass(); + + Method getHandleMethod = null; + try { + getHandleMethod = craftPlayerClass.getMethod("getHandle"); + } catch (NoSuchMethodException e) { + throw new RuntimeException(e); + } + + Object serverPlayer = null; + try { + serverPlayer = getHandleMethod.invoke(bukkitPlayer); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + + Class serverPlayerClass = MinecraftReflection.getEntityClass(); +// Arrays.stream(serverPlayerClass.getMethods()).toList().forEach(m -> Bukkit.broadcastMessage(m.getName() + ": " + String.join(",", Arrays.stream(m.getParameterTypes()).map(Class::getName).toList()))); + + Method setPosMethod = null; + try { + setPosMethod = serverPlayerClass.getMethod("setPosRaw", double.class, double.class, double.class, boolean.class); + } catch (NoSuchMethodException e) { + throw new RuntimeException(e); + } + + try { + setPosMethod.invoke(serverPlayer, x, y, z, false); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/Packet.java b/src/main/java/com/jverbruggen/jrides/packets/Packet.java new file mode 100644 index 00000000..c83e760d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/Packet.java @@ -0,0 +1,10 @@ +package com.jverbruggen.jrides.packets; + +import com.jverbruggen.jrides.models.entity.Player; + +import java.util.List; + +public interface Packet { + boolean send(Player player); + void sendAll(List players); +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/PacketSender.java b/src/main/java/com/jverbruggen/jrides/packets/PacketSender.java new file mode 100644 index 00000000..7e891c08 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/PacketSender.java @@ -0,0 +1,36 @@ +package com.jverbruggen.jrides.packets; + +import com.comphenix.protocol.wrappers.EnumWrappers; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.TrainModelItem; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.packets.object.VirtualArmorstandConfiguration; +import org.bukkit.entity.EntityType; + +import java.util.List; + +public interface PacketSender { + String getIdentifier(); + void spawnVirtualEntity(Player player, int entityId, Vector3 location, double yawRotation, + EntityType entityType, boolean invisible, int leashedToEntity); + void spawnVirtualArmorstand(Player player, int entityId, Vector3 location, double yawRotation, + VirtualArmorstandConfiguration configuration); + void spawnVirtualArmorstand(List players, int entityId, Vector3 location, double yawRotation, + VirtualArmorstandConfiguration configuration); + void spawnVirtualFallingBlock(Player player, int entityId, Vector3 location); + void sendRotationPacket(Player player, int entityId, int rotationType, Vector3 rotation); + void sendRotationPacket(List players, int entityId, int rotationType, Vector3 rotation); + void sendApplyModelPacket(Player player, int entityId, EnumWrappers.ItemSlot itemSlot, TrainModelItem model); + void sendApplyModelPacket(List players, int entityId, EnumWrappers.ItemSlot itemSlot, TrainModelItem model); + void sendAttachLeashPacket(Player player, int entityId, int leashToEntityId); + void moveVirtualArmorstand(Player player, int entityId, Vector3 location, double yawRotation); + void moveVirtualArmorstand(List players, int entityId, Vector3 location, double yawRotation); + void moveVirtualEntity(Player player, int entityId, Vector3 location, double yawRotation); + void moveVirtualEntity(List players, int entityId, Vector3 location, double yawRotation); + void destroyVirtualEntity(Player player, int entityId); + void destroyVirtualEntity(List players, int entityId); + void teleportVirtualEntity(Player player, int entityId, Vector3 blockLocation); + void teleportVirtualEntity(List players, int entityId, Vector3 blockLocation); + void sendMountVirtualEntityPacket(List players, Player mounted, int entityId); + void sendClientPositionPacket(Player movedPlayer, Vector3 position); +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/PacketSenderFactory.java b/src/main/java/com/jverbruggen/jrides/packets/PacketSenderFactory.java new file mode 100644 index 00000000..4ba9af06 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/PacketSenderFactory.java @@ -0,0 +1,30 @@ +package com.jverbruggen.jrides.packets; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.packets.impl.PacketSender_1_19_2; +import com.jverbruggen.jrides.packets.impl.PacketSender_1_20_1; +import com.jverbruggen.jrides.packets.impl.PacketSender_1_20_4; +import org.bukkit.Bukkit; + +public class PacketSenderFactory { + public static PacketSender getPacketSender(){ + String currentVersion = Bukkit.getVersion(); + boolean debugMode = false; + PacketSender packetSender = null; + + if(currentVersion.contains("1.19.2")){ + packetSender = new PacketSender_1_19_2(debugMode); + }else if(currentVersion.contains("1.20.4")){ + packetSender = new PacketSender_1_20_4(debugMode); + }else if(currentVersion.contains("1.20")){ + packetSender = new PacketSender_1_20_1(debugMode); + } + + if(packetSender == null) + throw new RuntimeException("No packet sender implemented for bukkit version '" + currentVersion + "'"); + + JRidesPlugin.getLogger().info("Using packet sender for '" + packetSender.getIdentifier() + "' (bukkit version '" + currentVersion + "')"); + + return packetSender; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/PacketType.java b/src/main/java/com/jverbruggen/jrides/packets/PacketType.java new file mode 100644 index 00000000..1fe32864 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/PacketType.java @@ -0,0 +1,5 @@ +package com.jverbruggen.jrides.packets; + +public enum PacketType { + SPAWN_VIRTUAL_ENTITY +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/impl/PacketSender_1_19_2.java b/src/main/java/com/jverbruggen/jrides/packets/impl/PacketSender_1_19_2.java new file mode 100644 index 00000000..3dfd0c62 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/impl/PacketSender_1_19_2.java @@ -0,0 +1,244 @@ +package com.jverbruggen.jrides.packets.impl; + +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.wrappers.EnumWrappers; +import com.jverbruggen.jrides.logging.JRidesLogger; +import com.jverbruggen.jrides.logging.LogType; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.TrainModelItem; +import com.jverbruggen.jrides.models.entity.armorstand.ArmorstandRotations; +import com.jverbruggen.jrides.models.entity.armorstand.ArmorstandModels; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.packets.PacketSender; +import com.jverbruggen.jrides.packets.object.VirtualArmorstandConfiguration; +import com.jverbruggen.jrides.packets.packet.v1_19.*; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.entity.EntityType; + +import java.util.List; +import java.util.UUID; + +public class PacketSender_1_19_2 implements PacketSender { + protected final ProtocolManager protocolManager; + protected final JRidesLogger logger; + protected final boolean debugMode; + + public PacketSender_1_19_2(boolean debugMode) { + this.logger = ServiceProvider.getSingleton(JRidesLogger.class); + this.protocolManager = ServiceProvider.getSingleton(ProtocolManager.class); + this.debugMode = debugMode; + } + + protected void sendDebugLog(String msg){ + if(debugMode) + logger.warning(msg); + } + + private void sendLog(String msg){ + logger.info(LogType.PACKET, msg); + } + + public void sendRotationPacket(Player player, int entityId, int rotationType, Vector3 rotation){ + sendDebugLog("sendRotationPacket (single)"); + + new ArmorstandRotationServerPacket( + protocolManager, entityId, rotationType, rotation + ).send(player); + } + + @Override + public void sendRotationPacket(List players, int entityId, int rotationType, Vector3 rotation) { + sendDebugLog("sendRotationPacket (multiple)"); + + new ArmorstandRotationServerPacket( + protocolManager, entityId, rotationType, rotation + ).sendAll(players); + } + + public void sendApplyModelPacket(Player player, int entityId, EnumWrappers.ItemSlot itemSlot, TrainModelItem model){ + if(model == null) return; + sendDebugLog("sendApplyModelPacket (single)"); + + new EntityEquipmentServerPacket( + protocolManager, entityId, itemSlot, model + ).send(player); + } + + @Override + public void sendApplyModelPacket(List players, int entityId, EnumWrappers.ItemSlot itemSlot, TrainModelItem model) { + if(model == null) return; + sendDebugLog("sendApplyModelPacket (multiple"); + + new EntityEquipmentServerPacket( + protocolManager, entityId, itemSlot, model + ).sendAll(players); + } + + public void sendAttachLeashPacket(Player player, int entityId, int leashToEntityId){ + if(leashToEntityId == -1) return; + sendDebugLog("sendAttachLeashPacket (single)"); + + new AttachEntityServerPacket( + protocolManager, entityId, leashToEntityId + ).send(player); + } + + @Override + public String getIdentifier() { + return "1.19.2"; + } + + @Override + public void spawnVirtualEntity(Player player, int entityId, Vector3 location, double yawRotation, EntityType entityType, boolean invisible, int leashedToEntity) { + sendDebugLog("spawnVirtualEntity (single)"); + + double locationX = location.getX(); + double locationY = location.getY(); + double locationZ = location.getZ(); + UUID uuid = UUID.randomUUID(); + + new SpawnBukkitEntityServerPacket( + protocolManager, entityId, entityType, locationX, locationY, locationZ, yawRotation, uuid + ).send(player); + + sendAttachLeashPacket(player, entityId, leashedToEntity); + } + + @Override + public void spawnVirtualArmorstand(Player player, int entityId, Vector3 location, double yawRotation, VirtualArmorstandConfiguration configuration) { + sendDebugLog("spawnVirtualArmorstand (single)"); + + double locationX = location.getX(); + double locationY = location.getY(); + double locationZ = location.getZ(); + UUID uuid = UUID.randomUUID(); + + boolean invisible = configuration.invisible(); + ArmorstandModels models = configuration.models(); + ArmorstandRotations rotations = configuration.rotations(); + int leashedToEntity = configuration.leashedToEntity(); + String customName = configuration.customName(); + + new SpawnArmorstandServerPacket( + protocolManager, entityId, locationX, locationY, locationZ, yawRotation, uuid + ).send(player); + + sendEntityMetaDataPacket(player, entityId, invisible, customName); + + sendApplyModelPacket(player, entityId, EnumWrappers.ItemSlot.HEAD, models.getHead()); + sendApplyModelPacket(player, entityId, EnumWrappers.ItemSlot.MAINHAND, models.getMainHand()); + sendApplyModelPacket(player, entityId, EnumWrappers.ItemSlot.OFFHAND, models.getOffHand()); + + sendRotationPacket(player, entityId, ArmorstandRotationServerPacket.Type.HEAD, rotations.getHead()); + sendRotationPacket(player, entityId, ArmorstandRotationServerPacket.Type.BODY, rotations.getBody()); + sendRotationPacket(player, entityId, ArmorstandRotationServerPacket.Type.OFF_HAND, rotations.getOffHand()); + sendRotationPacket(player, entityId, ArmorstandRotationServerPacket.Type.MAIN_HAND, rotations.getMainHand()); + sendRotationPacket(player, entityId, ArmorstandRotationServerPacket.Type.LEFT_LEG, rotations.getLeftLeg()); + sendRotationPacket(player, entityId, ArmorstandRotationServerPacket.Type.RIGHT_LEG, rotations.getRightLeg()); + + sendAttachLeashPacket(player, entityId, leashedToEntity); + } + + @Override + public void spawnVirtualArmorstand(List players, int entityId, Vector3 location, double yawRotation, VirtualArmorstandConfiguration configuration) { + sendDebugLog("spawnVirtualArmorstand (multiple)"); + + for(Player player : players){ + spawnVirtualArmorstand(player, entityId, location, yawRotation, configuration); + } + } + + @Override + public void spawnVirtualFallingBlock(Player player, int entityId, Vector3 location) { + sendDebugLog("spawnVirtualFallingBlock (single)"); + + throw new RuntimeException("Not implemented"); + } + + public void moveVirtualArmorstand(Player player, int entityId, Vector3 location, double yawRotation){ + sendDebugLog("moveVirtualArmorstand (single)"); + + new ArmorstandMoveServerPacket( + protocolManager, entityId, location, yawRotation + ).send(player); + } + + @Override + public void moveVirtualArmorstand(List players, int entityId, Vector3 location, double yawRotation) { + sendDebugLog("moveVirtualArmorstand (multiple)"); + + new ArmorstandMoveServerPacket( + protocolManager, entityId, location, yawRotation + ).sendAll(players); + } + + @Override + public void moveVirtualEntity(Player player, int entityId, Vector3 location, double yawRotation) { + sendDebugLog("moveVirtualEntity (single)"); + + new EntityMovePacket( + protocolManager, entityId, location, yawRotation + ).send(player); + } + + @Override + public void moveVirtualEntity(List players, int entityId, Vector3 location, double yawRotation) { + sendDebugLog("moveVirtualEntity (multiple)"); + + new EntityMovePacket( + protocolManager, entityId, location, yawRotation + ).sendAll(players); + } + + public void destroyVirtualEntity(Player player, int entityId){ + sendDebugLog("destroyVirtualEntity (single)"); + + new EntityDestroyServerPacket( + protocolManager, entityId + ).send(player); + } + + @Override + public void destroyVirtualEntity(List players, int entityId) { + sendDebugLog("destroyVirtualEntity (multiple)"); + + new EntityDestroyServerPacket( + protocolManager, entityId + ).sendAll(players); + } + + public void teleportVirtualEntity(Player player, int entityId, Vector3 blockLocation){ + sendDebugLog("teleportVirtualEntity (single)"); + + new EntityTeleportServerPacket(protocolManager, entityId, blockLocation).send(player); + } + + @Override + public void teleportVirtualEntity(List players, int entityId, Vector3 blockLocation) { + sendDebugLog("teleportVirtualEntity (multiple)"); + + new EntityTeleportServerPacket(protocolManager, entityId, blockLocation).sendAll(players); + } + + @Override + public void sendMountVirtualEntityPacket(List players, Player mounted, int entityId) { + sendDebugLog("sendMountVirtualEntityPacket (multiple)"); + + new EntityMountServerPacket(protocolManager, entityId, mounted).sendAll(players); + } + + @Override + public void sendClientPositionPacket(Player movedPlayer, Vector3 position) { + sendDebugLog("sendClientPositionPacket (single)"); + + new PlayerPositionServerPacket(protocolManager, position).send(movedPlayer); + } + + public void sendEntityMetaDataPacket(Player player, int entityId, boolean invisible, String customName){ + sendDebugLog("sendEntityMetaDataPacket (single)"); + + new EntityMetadataServerPacket( + protocolManager, entityId, invisible, customName + ).send(player); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/impl/PacketSender_1_20_1.java b/src/main/java/com/jverbruggen/jrides/packets/impl/PacketSender_1_20_1.java new file mode 100644 index 00000000..d42c4dd8 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/impl/PacketSender_1_20_1.java @@ -0,0 +1,45 @@ +package com.jverbruggen.jrides.packets.impl; + +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.packets.packet.v1_20.ArmorstandRotationServerPacket; +import com.jverbruggen.jrides.packets.packet.v1_20.EntityMetadataServerPacket; + +import java.util.List; + +public class PacketSender_1_20_1 extends PacketSender_1_19_2 { + public PacketSender_1_20_1(boolean debugMode) { + super(debugMode); + } + + public void sendRotationPacket(Player player, int entityId, int rotationType, Vector3 rotation){ + sendDebugLog("sendRotationPacket (single) 1.20.1"); + + new ArmorstandRotationServerPacket( + protocolManager, entityId, rotationType, rotation + ).send(player); + } + + @Override + public void sendRotationPacket(List players, int entityId, int rotationType, Vector3 rotation) { + sendDebugLog("sendRotationPacket (multiple) 1.20.1"); + + new ArmorstandRotationServerPacket( + protocolManager, entityId, rotationType, rotation + ).sendAll(players); + } + + @Override + public void sendEntityMetaDataPacket(Player player, int entityId, boolean invisible, String customName) { + sendDebugLog("sendEntityMetaDataPacket (single) 1.20.1"); + + new EntityMetadataServerPacket( + protocolManager, entityId, invisible, customName + ).send(player); + } + + @Override + public String getIdentifier() { + return "1.20.1"; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/impl/PacketSender_1_20_4.java b/src/main/java/com/jverbruggen/jrides/packets/impl/PacketSender_1_20_4.java new file mode 100644 index 00000000..2d408cd3 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/impl/PacketSender_1_20_4.java @@ -0,0 +1,12 @@ +package com.jverbruggen.jrides.packets.impl; + +public class PacketSender_1_20_4 extends PacketSender_1_20_1 { + public PacketSender_1_20_4(boolean debugMode) { + super(debugMode); + } + + @Override + public String getIdentifier() { + return "1.20.4"; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/listener/VirtualEntityPacketListener.java b/src/main/java/com/jverbruggen/jrides/packets/listener/VirtualEntityPacketListener.java new file mode 100644 index 00000000..ff548bed --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/listener/VirtualEntityPacketListener.java @@ -0,0 +1,216 @@ +package com.jverbruggen.jrides.packets.listener; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.events.ListenerPriority; +import com.comphenix.protocol.events.PacketAdapter; +import com.comphenix.protocol.events.PacketEvent; +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.smoothanimation.SmoothAnimation; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.SeatedOnContext; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.ride.Ride; +import com.jverbruggen.jrides.models.ride.seat.InstructionType; +import com.jverbruggen.jrides.models.ride.seat.Seat; +import com.jverbruggen.jrides.common.permissions.Permissions; +import com.jverbruggen.jrides.models.ride.coaster.train.CoasterSeat; +import com.jverbruggen.jrides.packets.PacketSender; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.player.PlayerManager; +import com.jverbruggen.jrides.state.viewport.ViewportManager; +import org.bukkit.Bukkit; +import org.bukkit.event.Listener; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +public class VirtualEntityPacketListener extends PacketAdapter implements Listener { + private final ViewportManager viewportManager; + private final PlayerManager playerManager; + private final SmoothAnimation smoothAnimation; + private final List shiftPressedDebounce; + private final PacketSender packetSender; + private final LanguageFile languageFile; + + public VirtualEntityPacketListener() { + super(JRidesPlugin.getBukkitPlugin(), ListenerPriority.NORMAL, + PacketType.Play.Client.USE_ENTITY, + PacketType.Play.Client.STEER_VEHICLE, + PacketType.Play.Server.NAMED_ENTITY_SPAWN); + this.viewportManager = ServiceProvider.getSingleton(ViewportManager.class); + this.playerManager = ServiceProvider.getSingleton(PlayerManager.class); + this.smoothAnimation = ServiceProvider.getSingleton(SmoothAnimation.class); + this.packetSender = ServiceProvider.getSingleton(PacketSender.class); + this.shiftPressedDebounce = new ArrayList<>(); + this.languageFile = ServiceProvider.getSingleton(LanguageFile.class); + } + + @Override + public void onPacketReceiving(PacketEvent event) { + PacketType packetType = event.getPacketType(); + if (packetType.equals(PacketType.Play.Client.USE_ENTITY)) { + onUseEntity(event); + } else if (packetType.equals(PacketType.Play.Client.STEER_VEHICLE)) { + onSteerVehicle(event); + } + } + + @Override + public void onPacketSending(PacketEvent event) { + PacketType packetType = event.getPacketType(); + if(packetType.equals(PacketType.Play.Server.NAMED_ENTITY_SPAWN)){ + onSendingSpawnPlayerPacket(event); + } + } + + private void onUseEntity(PacketEvent event) { + int entityId = event.getPacket().getIntegers().read(0); + VirtualEntity entity = viewportManager.getEntity(entityId); + org.bukkit.entity.Player bukkitPlayer = event.getPlayer(); + + if (entity == null) { + return; + } + Player player = playerManager.getPlayer(bukkitPlayer); + if (entity.hasCustomAction()){ + entity.runCustomAction(player); + } + if (!entity.allowsPassenger()) { + return; + } + if (bukkitPlayer.getLocation().toVector().distanceSquared(entity.getLocation().toBukkitVector()) > 49) { + return; + } + + Seat seat = entity.getHostSeat(); + + if(seat == null) return; + if(player.isSeated()) return; + + if(!seat.getParentRideHandle().isOpen() + && !player.hasPermission(Permissions.ELEVATED_RIDE_CLOSED_ENTER_OVERRIDE)){ + languageFile.sendMessage(player, LanguageFileField.NOTIFICATION_CANNOT_ENTER_RIDE_CLOSED); + return; + } + + if(seat.restraintsActive()){ + if(!player.getBukkitPlayer().hasPermission(Permissions.ELEVATED_RESTRAINT_OVERRIDE)){ + languageFile.sendMessage(player, LanguageFileField.NOTIFICATION_RESTRAINT_ON_ENTER_ATTEMPT); + return; + } + languageFile.sendMessage(player, LanguageFileField.NOTIFICATION_RESTRAINT_ENTER_OVERRIDE); + } + + player.setSmoothAnimationSupport(smoothAnimation.isEnabled(player)); + seat.setPassenger(player); + } + + private void processPlayerControl(PacketEvent event, Seat seat){ + if(seat == null || !seat.supportsPlayerControl()){ + return; + } + + float sidewaysLeft = event.getPacket().getFloat().read(0); // Left is positive, right is negative + float forwards = event.getPacket().getFloat().read(1); + boolean jump = event.getPacket().getBooleans().read(0); + + InstructionType type; + if(sidewaysLeft > 0){ + type = InstructionType.A; + }else if(sidewaysLeft < 0){ + type = InstructionType.D; + }else if(forwards > 0){ + type = InstructionType.W; + }else if(forwards < 0){ + type = InstructionType.S; + }else if(jump){ + type = InstructionType.SPACE; + }else{ + type = InstructionType.NONE; + } + + seat.sendPlayerControlInstruction(type); + } + + private void onSteerVehicle(PacketEvent event) { + boolean dismountVehicle = event.getPacket().getBooleans().read(1); + + org.bukkit.entity.Player bukkitPlayer = event.getPlayer(); + Player player = playerManager.getPlayer(bukkitPlayer); + SeatedOnContext seatedOnContext = player.getSeatedOnContext(); + if(seatedOnContext == null) return; + + Seat seat = seatedOnContext.getSeat(); + + processPlayerControl(event, seat); + + if(!dismountVehicle){ + removeShiftDebounce(event.getPlayer()); + return; + } + + if(seat == null){ + return; + } + + VirtualEntity entity = seat.getEntity(); + + if(entity.getPassenger() == null) return; + if(!entity.getPassenger().getBukkitPlayer().getUniqueId().equals(bukkitPlayer.getUniqueId())){ + return; // Can only steer vehicle that one is in + } + + UUID uuid = bukkitPlayer.getUniqueId(); + if(shiftPressedDebounce.contains(uuid)) return; + shiftPressedDebounce.add(uuid); + + double teleportYaw = player.getBukkitPlayer().getLocation().getYaw(); + Ride ride = seat.getParentRideHandle().getRide(); + + if(seat.restraintsActive()){ + if(bukkitPlayer.hasPermission(Permissions.ELEVATED_RESTRAINT_OVERRIDE)){ + Bukkit.getScheduler().runTask(JRidesPlugin.getBukkitPlugin(), () -> { + boolean ejected = seat.ejectPassengerSoft(false); + if(ejected){ + languageFile.sendMessage(player, LanguageFileField.NOTIFICATION_SHIFT_EXIT_CONFIRMED); + player.teleport(Vector3.add(entity.getLocation(), CoasterSeat.getHeightCompensation()), teleportYaw); + } + }); + return; + }else if(ride.canExitDuringRide()){ + Bukkit.getScheduler().runTask(JRidesPlugin.getBukkitPlugin(), () -> seat.ejectPassengerSoft(true)); + return; + } + + languageFile.sendMessage(player, LanguageFileField.NOTIFICATION_RESTRAINT_ON_EXIT_ATTEMPT); + return; + } + + Bukkit.getScheduler().runTask(JRidesPlugin.getBukkitPlugin(), () -> { + seat.setPassenger(null); + player.teleport(Vector3.add(entity.getLocation(), CoasterSeat.getHeightCompensation()), teleportYaw); + }); + } + + private void removeShiftDebounce(org.bukkit.entity.Player player){ + if(shiftPressedDebounce.size() > 0) shiftPressedDebounce.remove(player.getUniqueId()); + } + + private void onSendingSpawnPlayerPacket(PacketEvent event){ + UUID uuid = event.getPacket().getUUIDs().read(0); + + org.bukkit.entity.Player bukkitPlayer = Bukkit.getPlayer(uuid); + if(bukkitPlayer == null) return; + Player player = playerManager.getPlayer(bukkitPlayer); + if(!player.isSeated()) return; + + Player receiver = playerManager.getPlayer(event.getPlayer()); + + Bukkit.getScheduler().runTaskLater(JRidesPlugin.getBukkitPlugin(), + () -> packetSender.sendMountVirtualEntityPacket(List.of(receiver), player, player.getSeatedOn().getEntity().getEntityId()), 1L); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/object/VirtualArmorstandConfiguration.java b/src/main/java/com/jverbruggen/jrides/packets/object/VirtualArmorstandConfiguration.java new file mode 100644 index 00000000..bb3dc67f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/object/VirtualArmorstandConfiguration.java @@ -0,0 +1,22 @@ +package com.jverbruggen.jrides.packets.object; + +import com.jverbruggen.jrides.models.entity.armorstand.ArmorstandModels; +import com.jverbruggen.jrides.models.entity.armorstand.ArmorstandRotations; + +public record VirtualArmorstandConfiguration( + ArmorstandRotations rotations, + ArmorstandModels models, + boolean invisible, + int leashedToEntity, + String customName) { + private static final int DEFAULT_LEASHED_TO_VALUE = -1; + private static final boolean DEFAULT_INVISIBLE = true; + + public static VirtualArmorstandConfiguration createWithName(String customName){ + return new VirtualArmorstandConfiguration(new ArmorstandRotations(), new ArmorstandModels(), DEFAULT_INVISIBLE, DEFAULT_LEASHED_TO_VALUE, customName); + } + + public static VirtualArmorstandConfiguration createDefault(){ + return new VirtualArmorstandConfiguration(new ArmorstandRotations(), new ArmorstandModels(), DEFAULT_INVISIBLE, DEFAULT_LEASHED_TO_VALUE, null); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/packet/MultiplePacket.java b/src/main/java/com/jverbruggen/jrides/packets/packet/MultiplePacket.java new file mode 100644 index 00000000..25be55f8 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/packet/MultiplePacket.java @@ -0,0 +1,40 @@ +package com.jverbruggen.jrides.packets.packet; + +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.packets.Packet; + +import java.util.List; + +public abstract class MultiplePacket implements Packet { + protected ProtocolManager protocolManager; + + public MultiplePacket(ProtocolManager protocolManager) { + this.protocolManager = protocolManager; + } + + public abstract List getPackets(); + + protected boolean sendPacket(Player player, PacketContainer packet){ + this.protocolManager.sendServerPacket(player.getBukkitPlayer(), packet); + return true; + } + + @Override + public boolean send(Player player) { + for(PacketContainer packet : getPackets()){ + sendPacket(player, packet); + } + return true; + } + + @Override + public void sendAll(List players) { + for(PacketContainer packet : getPackets()){ + for(Player player : players){ + sendPacket(player, packet); + } + } + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/packet/SingularClientPacket.java b/src/main/java/com/jverbruggen/jrides/packets/packet/SingularClientPacket.java new file mode 100644 index 00000000..011372c7 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/packet/SingularClientPacket.java @@ -0,0 +1,36 @@ +package com.jverbruggen.jrides.packets.packet; + +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.packets.Packet; + +import java.util.List; + +public abstract class SingularClientPacket implements Packet { + protected ProtocolManager protocolManager; + + public SingularClientPacket(ProtocolManager protocolManager) { + this.protocolManager = protocolManager; + } + + public abstract PacketContainer getPacket(); + + protected boolean sendPacket(Player player, PacketContainer packet){ + this.protocolManager.receiveClientPacket(player.getBukkitPlayer(), packet); + return true; + } + + @Override + public boolean send(Player player) { + return sendPacket(player, getPacket()); + } + + @Override + public void sendAll(List players) { + PacketContainer packet = getPacket(); + for(Player player : players){ + sendPacket(player, packet); + } + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/packet/SingularServerPacket.java b/src/main/java/com/jverbruggen/jrides/packets/packet/SingularServerPacket.java new file mode 100644 index 00000000..b65b542a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/packet/SingularServerPacket.java @@ -0,0 +1,36 @@ +package com.jverbruggen.jrides.packets.packet; + +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.packets.Packet; + +import java.util.List; + +public abstract class SingularServerPacket implements Packet { + protected ProtocolManager protocolManager; + + public SingularServerPacket(ProtocolManager protocolManager) { + this.protocolManager = protocolManager; + } + + public abstract PacketContainer getPacket(); + + protected boolean sendPacket(Player player, PacketContainer packet){ + this.protocolManager.sendServerPacket(player.getBukkitPlayer(), packet); + return true; + } + + @Override + public boolean send(Player player) { + return sendPacket(player, getPacket()); + } + + @Override + public void sendAll(List players) { + PacketContainer packet = getPacket(); + for(Player player : players){ + sendPacket(player, packet); + } + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/ArmorstandMoveServerPacket.java b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/ArmorstandMoveServerPacket.java new file mode 100644 index 00000000..bae0eeae --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/ArmorstandMoveServerPacket.java @@ -0,0 +1,38 @@ +package com.jverbruggen.jrides.packets.packet.v1_19; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.packets.packet.SingularServerPacket; +import com.jverbruggen.jrides.packets.Packet; + +public class ArmorstandMoveServerPacket extends SingularServerPacket implements Packet { + private int entityId; + private Vector3 location; + private double yawRotation; + + public ArmorstandMoveServerPacket(ProtocolManager protocolManager, int entityId, Vector3 location, double yawRotation) { + super(protocolManager); + this.entityId = entityId; + this.location = location; + this.yawRotation = yawRotation; + } + + @Override + public PacketContainer getPacket(){ + PacketContainer packet = new PacketContainer(PacketType.Play.Server.REL_ENTITY_MOVE_LOOK); + packet.getIntegers() + .write(0, entityId); + packet.getShorts() + .write(0, (short)((location.getX() * 32) * 128)) + .write(1, (short)((location.getY() * 32) * 128)) + .write(2, (short)((location.getZ() * 32) * 128)); + packet.getBytes() + .write(0, (byte)(yawRotation)); + packet.getBooleans() + .write(0, false); + + return packet; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/ArmorstandRotationServerPacket.java b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/ArmorstandRotationServerPacket.java new file mode 100644 index 00000000..a36ab472 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/ArmorstandRotationServerPacket.java @@ -0,0 +1,44 @@ +package com.jverbruggen.jrides.packets.packet.v1_19; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.wrappers.WrappedDataWatcher; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.packets.packet.SingularServerPacket; +import com.jverbruggen.jrides.packets.Packet; + +public class ArmorstandRotationServerPacket extends SingularServerPacket implements Packet { + public static class Type{ + public static final int HEAD = 16; + public static final int BODY = 17; + public static final int OFF_HAND = 18; + public static final int MAIN_HAND = 19; + public static final int LEFT_LEG = 20; + public static final int RIGHT_LEG = 21; + } + + protected final int entityId; + protected final int rotationType; + protected final Vector3 rotation; + + public ArmorstandRotationServerPacket(ProtocolManager protocolManager, int entityId, int rotationType, Vector3 rotation) { + super(protocolManager); + this.entityId = entityId; + this.rotationType = rotationType; + this.rotation = rotation; + } + + @Override + public PacketContainer getPacket() { + PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA); + packet.getIntegers().write(0, this.entityId); + + WrappedDataWatcher watcher = new WrappedDataWatcher(); + WrappedDataWatcher.Serializer serializer = WrappedDataWatcher.Registry.getVectorSerializer(); + watcher.setObject(rotationType, serializer, rotation.toVector3F()); + packet.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects()); + + return packet; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/AttachEntityServerPacket.java b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/AttachEntityServerPacket.java new file mode 100644 index 00000000..fdfc542a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/AttachEntityServerPacket.java @@ -0,0 +1,28 @@ +package com.jverbruggen.jrides.packets.packet.v1_19; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.jverbruggen.jrides.packets.packet.SingularServerPacket; +import com.jverbruggen.jrides.packets.Packet; + +public class AttachEntityServerPacket extends SingularServerPacket implements Packet { + private int entityId; + private int leashedToEntityId; + + public AttachEntityServerPacket(ProtocolManager protocolManager, int entityId, int leashedToEntityId) { + super(protocolManager); + this.entityId = entityId; + this.leashedToEntityId = leashedToEntityId; + } + + @Override + public PacketContainer getPacket() { + PacketContainer leashPacket = new PacketContainer(PacketType.Play.Server.ATTACH_ENTITY); + leashPacket.getIntegers() + .write(0, entityId) + .write(1, leashedToEntityId); + + return leashPacket; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/EntityDestroyServerPacket.java b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/EntityDestroyServerPacket.java new file mode 100644 index 00000000..0536f9a4 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/EntityDestroyServerPacket.java @@ -0,0 +1,30 @@ +package com.jverbruggen.jrides.packets.packet.v1_19; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.jverbruggen.jrides.packets.packet.SingularServerPacket; +import com.jverbruggen.jrides.packets.Packet; + +import java.util.ArrayList; +import java.util.List; + +public class EntityDestroyServerPacket extends SingularServerPacket implements Packet { + private int entityId; + + public EntityDestroyServerPacket(ProtocolManager protocolManager, int entityId) { + super(protocolManager); + this.entityId = entityId; + } + + @Override + public PacketContainer getPacket() { + PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_DESTROY); + List toDestroy = new ArrayList<>(); + toDestroy.add(this.entityId); + packet.getIntLists() + .write(0, toDestroy); + + return packet; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/EntityEquipmentServerPacket.java b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/EntityEquipmentServerPacket.java new file mode 100644 index 00000000..c3e5df9b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/EntityEquipmentServerPacket.java @@ -0,0 +1,38 @@ +package com.jverbruggen.jrides.packets.packet.v1_19; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.wrappers.EnumWrappers; +import com.comphenix.protocol.wrappers.Pair; +import com.jverbruggen.jrides.models.entity.TrainModelItem; +import com.jverbruggen.jrides.packets.packet.SingularServerPacket; +import com.jverbruggen.jrides.packets.Packet; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class EntityEquipmentServerPacket extends SingularServerPacket implements Packet { + private final int entityId; + private final EnumWrappers.ItemSlot itemSlot; + private final TrainModelItem model; + + public EntityEquipmentServerPacket(ProtocolManager protocolManager, int entityId, EnumWrappers.ItemSlot itemSlot, TrainModelItem model) { + super(protocolManager); + this.entityId = entityId; + this.itemSlot = itemSlot; + this.model = model; + } + + @Override + public PacketContainer getPacket() { + PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_EQUIPMENT); + packet.getIntegers().write(0, this.entityId); + List> data = new ArrayList<>(); + data.add(new Pair<>(itemSlot, model.getItemStack())); + packet.getSlotStackPairLists().write(0, data); + + return packet; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/EntityMetadataServerPacket.java b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/EntityMetadataServerPacket.java new file mode 100644 index 00000000..18d17fcb --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/EntityMetadataServerPacket.java @@ -0,0 +1,54 @@ +package com.jverbruggen.jrides.packets.packet.v1_19; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.wrappers.WrappedChatComponent; +import com.comphenix.protocol.wrappers.WrappedDataWatcher; +import com.jverbruggen.jrides.packets.packet.SingularServerPacket; +import com.jverbruggen.jrides.packets.Packet; + +import java.util.Optional; + +/** + * Pre < 1.19 + */ +public class EntityMetadataServerPacket extends SingularServerPacket implements Packet { + private final int entityId; + private final boolean invisible; + private final String customName; + + public EntityMetadataServerPacket(ProtocolManager protocolManager, int entityId, boolean invisible, String customName) { + super(protocolManager); + this.entityId = entityId; + this.invisible = invisible; + this.customName = customName; + } + + @Override + public PacketContainer getPacket() { + byte modifier = 0x0; + if(this.invisible) modifier |= 0x20; + + return createMetaDataPacket(this.entityId, modifier, this.customName); + } + + protected PacketContainer createMetaDataPacket(int entityId, byte modifier, String customName){ + PacketContainer metaDataPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA); + metaDataPacket.getIntegers().write(0, entityId); + boolean customNameVisible = customName != null; + + WrappedDataWatcher watcher = new WrappedDataWatcher(); + watcher.setObject(0, WrappedDataWatcher.Registry.get(Byte.class), modifier); + if(customNameVisible){ + watcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(2, WrappedDataWatcher.Registry.getChatComponentSerializer(true)), + Optional.of(WrappedChatComponent.fromText(customName).getHandle())); + } + watcher.setObject(new WrappedDataWatcher.WrappedDataWatcherObject(3, WrappedDataWatcher.Registry.get(Boolean.class)), + customNameVisible); + + metaDataPacket.getWatchableCollectionModifier().write(0, watcher.getWatchableObjects()); + + return metaDataPacket; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/EntityMountServerPacket.java b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/EntityMountServerPacket.java new file mode 100644 index 00000000..2b89fad3 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/EntityMountServerPacket.java @@ -0,0 +1,36 @@ +package com.jverbruggen.jrides.packets.packet.v1_19; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.packets.Packet; +import com.jverbruggen.jrides.packets.packet.SingularServerPacket; + +public class EntityMountServerPacket extends SingularServerPacket implements Packet { + private final int entityId; + private final Player mountedPlayer; + + public EntityMountServerPacket(ProtocolManager protocolManager, int entityId, Player mountedPlayer) { + super(protocolManager); + + this.entityId = entityId; + this.mountedPlayer = mountedPlayer; + } + + @Override + public PacketContainer getPacket() { + int[] mountingEntity; + if(mountedPlayer != null){ + mountingEntity = new int[]{mountedPlayer.getBukkitPlayer().getEntityId()}; + }else{ + mountingEntity = new int[]{}; + } + + PacketContainer packet = new PacketContainer(PacketType.Play.Server.MOUNT); + packet.getIntegers().write(0, entityId); + packet.getIntegerArrays().write(0, mountingEntity); + + return packet; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/EntityMovePacket.java b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/EntityMovePacket.java new file mode 100644 index 00000000..fdfb261f --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/EntityMovePacket.java @@ -0,0 +1,51 @@ +package com.jverbruggen.jrides.packets.packet.v1_19; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.packets.packet.MultiplePacket; +import com.jverbruggen.jrides.packets.Packet; + +import java.util.LinkedList; +import java.util.List; + +public class EntityMovePacket extends MultiplePacket implements Packet { + private int entityId; + private Vector3 location; + private double yawRotation; + + public EntityMovePacket(ProtocolManager protocolManager, int entityId, Vector3 location, double yawRotation) { + super(protocolManager); + this.entityId = entityId; + this.location = location; + this.yawRotation = yawRotation; + } + + @Override + public List getPackets() { + PacketContainer packet = new PacketContainer(PacketType.Play.Server.REL_ENTITY_MOVE_LOOK); + packet.getIntegers() + .write(0, entityId); + packet.getShorts() + .write(0, (short)((location.getX() * 32) * 128)) + .write(1, (short)((location.getY() * 32) * 128)) + .write(2, (short)((location.getZ() * 32) * 128)); + packet.getBytes() + .write(0, (byte)(yawRotation)); + packet.getBooleans() + .write(0, false); + + PacketContainer rotationPacket = new PacketContainer(PacketType.Play.Server.ENTITY_HEAD_ROTATION); + rotationPacket.getIntegers() + .write(0, entityId); + rotationPacket.getBytes() + .write(0, (byte) yawRotation); + + List packets = new LinkedList<>(); + packets.add(packet); + packets.add(rotationPacket); + + return packets; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/EntityTeleportServerPacket.java b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/EntityTeleportServerPacket.java new file mode 100644 index 00000000..db350699 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/EntityTeleportServerPacket.java @@ -0,0 +1,34 @@ +package com.jverbruggen.jrides.packets.packet.v1_19; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.packets.Packet; +import com.jverbruggen.jrides.packets.packet.SingularServerPacket; + +public class EntityTeleportServerPacket extends SingularServerPacket implements Packet { + private int entityId; + private Vector3 location; + + public EntityTeleportServerPacket(ProtocolManager protocolManager, int entityId, Vector3 location) { + super(protocolManager); + this.entityId = entityId; + this.location = location; + } + + @Override + public PacketContainer getPacket() { + PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_TELEPORT); + packet.getIntegers() + .write(0, this.entityId); + packet.getDoubles() + .write(0, (double) (location.getBlockX())) + .write(1, (double) (location.getBlockY())) + .write(2, (double) (location.getBlockZ())); + packet.getBooleans() + .write(0, false); + + return packet; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/PlayerPositionServerPacket.java b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/PlayerPositionServerPacket.java new file mode 100644 index 00000000..c1fef228 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/PlayerPositionServerPacket.java @@ -0,0 +1,29 @@ +package com.jverbruggen.jrides.packets.packet.v1_19; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.packets.Packet; +import com.jverbruggen.jrides.packets.packet.SingularClientPacket; + +public class PlayerPositionServerPacket extends SingularClientPacket implements Packet { + private final Vector3 position; + + public PlayerPositionServerPacket(ProtocolManager protocolManager, Vector3 position) { + super(protocolManager); + + this.position = position; + } + + @Override + public PacketContainer getPacket() { + PacketContainer packet = new PacketContainer(PacketType.Play.Client.POSITION); + packet.getDoubles() + .write(0, position.getX()) + .write(1, position.getY()) + .write(2, position.getZ()); + + return packet; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/SpawnArmorstandServerPacket.java b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/SpawnArmorstandServerPacket.java new file mode 100644 index 00000000..fa30d3ad --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/SpawnArmorstandServerPacket.java @@ -0,0 +1,48 @@ +package com.jverbruggen.jrides.packets.packet.v1_19; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.jverbruggen.jrides.packets.Packet; +import com.jverbruggen.jrides.packets.packet.SingularServerPacket; +import org.bukkit.entity.EntityType; + +import java.util.UUID; + +public class SpawnArmorstandServerPacket extends SingularServerPacket implements Packet { + private int entityId; + private double locationX; + private double locationY; + private double locationZ; + private double yawRotation; + private UUID uuid; + + public SpawnArmorstandServerPacket(ProtocolManager protocolManager, int entityId, double locationX, double locationY, double locationZ, double yawRotation, UUID uuid) { + super(protocolManager); + this.entityId = entityId; + this.locationX = locationX; + this.locationY = locationY; + this.locationZ = locationZ; + this.yawRotation = yawRotation; + this.uuid = uuid; + } + + @Override + public PacketContainer getPacket() { + PacketContainer packet = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY); + packet.getIntegers() + .write(0, entityId); + packet.getEntityTypeModifier() + .write(0, EntityType.ARMOR_STAND); + packet.getDoubles() + .write(0, locationX) + .write(1, locationY) + .write(2, locationZ); + packet.getBytes() + .write(1, (byte)yawRotation); + packet.getUUIDs() + .write(0, uuid); + + return packet; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/SpawnBukkitEntityServerPacket.java b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/SpawnBukkitEntityServerPacket.java new file mode 100644 index 00000000..f62b4a36 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_19/SpawnBukkitEntityServerPacket.java @@ -0,0 +1,50 @@ +package com.jverbruggen.jrides.packets.packet.v1_19; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.jverbruggen.jrides.packets.Packet; +import com.jverbruggen.jrides.packets.packet.SingularServerPacket; +import org.bukkit.entity.EntityType; + +import java.util.UUID; + +public class SpawnBukkitEntityServerPacket extends SingularServerPacket implements Packet { + private int entityId; + private EntityType entityType; + private double locationX; + private double locationY; + private double locationZ; + private double yawRotation; + private UUID uuid; + + public SpawnBukkitEntityServerPacket(ProtocolManager protocolManager, int entityId, EntityType entityType, double locationX, double locationY, double locationZ, double yawRotation, UUID uuid) { + super(protocolManager); + this.entityId = entityId; + this.entityType = entityType; + this.locationX = locationX; + this.locationY = locationY; + this.locationZ = locationZ; + this.yawRotation = yawRotation; + this.uuid = uuid; + } + + @Override + public PacketContainer getPacket() { + PacketContainer packet = new PacketContainer(PacketType.Play.Server.SPAWN_ENTITY); + packet.getIntegers() + .write(0, entityId); + packet.getEntityTypeModifier() + .write(0, entityType); + packet.getDoubles() + .write(0, locationX) + .write(1, locationY) + .write(2, locationZ); + packet.getBytes() + .write(1, (byte)yawRotation); + packet.getUUIDs() + .write(0, uuid); + + return packet; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/packet/v1_20/ArmorstandRotationServerPacket.java b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_20/ArmorstandRotationServerPacket.java new file mode 100644 index 00000000..4de50bcd --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_20/ArmorstandRotationServerPacket.java @@ -0,0 +1,35 @@ +package com.jverbruggen.jrides.packets.packet.v1_20; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.wrappers.WrappedDataValue; +import com.comphenix.protocol.wrappers.WrappedDataWatcher; +import com.google.common.collect.Lists; +import com.jverbruggen.jrides.models.math.Vector3; + +import java.util.List; + +public class ArmorstandRotationServerPacket extends com.jverbruggen.jrides.packets.packet.v1_19.ArmorstandRotationServerPacket { + public ArmorstandRotationServerPacket(ProtocolManager protocolManager, int entityId, int rotationType, Vector3 rotation) { + super(protocolManager, entityId, rotationType, rotation); + } + + @Override + public PacketContainer getPacket() { + PacketContainer packet = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA); + packet.getIntegers().write(0, this.entityId); + + WrappedDataWatcher.Serializer serializer = WrappedDataWatcher.Registry.getVectorSerializer(); + + WrappedDataValue value = new WrappedDataValue(rotationType, serializer, null); + value.setValue(rotation.toVector3F()); + List values = Lists.newArrayList( + value + ); + + packet.getDataValueCollectionModifier().write(0, values); + + return packet; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/packets/packet/v1_20/EntityMetadataServerPacket.java b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_20/EntityMetadataServerPacket.java new file mode 100644 index 00000000..7e6196a7 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/packets/packet/v1_20/EntityMetadataServerPacket.java @@ -0,0 +1,43 @@ +package com.jverbruggen.jrides.packets.packet.v1_20; + +import com.comphenix.protocol.PacketType; +import com.comphenix.protocol.ProtocolManager; +import com.comphenix.protocol.events.PacketContainer; +import com.comphenix.protocol.wrappers.WrappedChatComponent; +import com.comphenix.protocol.wrappers.WrappedDataValue; +import com.comphenix.protocol.wrappers.WrappedDataWatcher; +import com.google.common.collect.Lists; + +import java.util.List; +import java.util.Optional; + +/** + * 1.20 - current + */ +public class EntityMetadataServerPacket extends com.jverbruggen.jrides.packets.packet.v1_19.EntityMetadataServerPacket { + public EntityMetadataServerPacket(ProtocolManager protocolManager, int entityId, boolean invisible, String customName) { + super(protocolManager, entityId, invisible, customName); + } + + @Override + protected PacketContainer createMetaDataPacket(int entityId, byte modifier, String customName){ + PacketContainer metaDataPacket = new PacketContainer(PacketType.Play.Server.ENTITY_METADATA); + metaDataPacket.getIntegers().write(0, entityId); + + WrappedDataWatcher.Serializer serializer = WrappedDataWatcher.Registry.get(Byte.class); + + boolean customNameVisible = customName != null; + + List values = Lists.newArrayList( + new WrappedDataValue(0, serializer, modifier), + new WrappedDataValue(3, WrappedDataWatcher.Registry.get(Boolean.class), customNameVisible) + ); + + if (customNameVisible) + values.add(new WrappedDataValue(2, WrappedDataWatcher.Registry.getChatComponentSerializer(true), Optional.of(WrappedChatComponent.fromText(customName).getHandle()))); + + metaDataPacket.getDataValueCollectionModifier().write(0, values); + + return metaDataPacket; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/serviceprovider/HashMapServiceProvider.java b/src/main/java/com/jverbruggen/jrides/serviceprovider/HashMapServiceProvider.java new file mode 100644 index 00000000..9748bb77 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/serviceprovider/HashMapServiceProvider.java @@ -0,0 +1,32 @@ +package com.jverbruggen.jrides.serviceprovider; + +import java.util.HashMap; +import java.util.function.Function; + +@SuppressWarnings("rawtypes") +public class HashMapServiceProvider implements ServiceProvider { + + private HashMap instances; + + public HashMapServiceProvider() { + this.instances = new HashMap<>(); + } + + @Override + public T _getSingleton(Class type) { + if(!instances.containsKey(type)) throw new RuntimeException("Type " + type.getTypeName() + " was not registered to the ServiceProvider"); + + Object object = instances.get(type); + return (T) object; + } + + @Override + public void _register(Class type, Object instance) { + instances.put(type, instance); + } + + @Override + public void _register(Class type, Function function) { + function.apply((T) this); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/serviceprovider/ServiceProvider.java b/src/main/java/com/jverbruggen/jrides/serviceprovider/ServiceProvider.java new file mode 100644 index 00000000..c091bebb --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/serviceprovider/ServiceProvider.java @@ -0,0 +1,26 @@ +package com.jverbruggen.jrides.serviceprovider; + +import java.util.function.Function; + +@SuppressWarnings("rawtypes") +public interface ServiceProvider { + T _getSingleton(Class type); + + void _register(Class type, Object instance); + void _register(Class type, Function function); + + ServiceProvider instance = new HashMapServiceProvider(); + + static T getSingleton(Class type){ + return instance._getSingleton(type); + } + + static R register(Class type, R o){ + instance._register(type, o); + return o; + } + + static void registerWith(Class type, Function function){ + instance._register(type, function); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/serviceprovider/configuration/ServiceProviderConfigurator.java b/src/main/java/com/jverbruggen/jrides/serviceprovider/configuration/ServiceProviderConfigurator.java new file mode 100644 index 00000000..2ad42a55 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/serviceprovider/configuration/ServiceProviderConfigurator.java @@ -0,0 +1,105 @@ +package com.jverbruggen.jrides.serviceprovider.configuration; + +import com.comphenix.protocol.ProtocolLibrary; +import com.comphenix.protocol.ProtocolManager; +import com.jverbruggen.jrides.animator.flatride.factory.FlatRideFactory; +import com.jverbruggen.jrides.animator.smoothanimation.SmoothAnimation; +import com.jverbruggen.jrides.animator.smoothanimation.SmoothCoastersSmoothAnimation; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.factory.TrackBehaviourFactory; +import com.jverbruggen.jrides.animator.coaster.trackbehaviour.result.CartMovementFactory; +import com.jverbruggen.jrides.common.MenuSessionManager; +import com.jverbruggen.jrides.config.ConfigManager; +import com.jverbruggen.jrides.config.trigger.TriggerConfigFactory; +import com.jverbruggen.jrides.control.controller.RideControllerFactory; +import com.jverbruggen.jrides.control.controlmode.factory.ControlModeFactory; +import com.jverbruggen.jrides.control.uiinterface.menu.RideControlMenuFactory; +import com.jverbruggen.jrides.control.uiinterface.menu.button.controller.ButtonUpdateController; +import com.jverbruggen.jrides.control.uiinterface.menu.button.factory.RideControlButtonFactory; +import com.jverbruggen.jrides.effect.EffectTriggerFactory; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.logging.JRidesLogger; +import com.jverbruggen.jrides.models.entity.EntityIdFactory; +import com.jverbruggen.jrides.models.entity.agent.MessageAgentManager; +import com.jverbruggen.jrides.models.map.ridecounter.RideCounterMapFactory; +import com.jverbruggen.jrides.models.map.rideoverview.RideOverviewMapFactory; +import com.jverbruggen.jrides.models.map.rideoverview.SectionVisualFactory; +import com.jverbruggen.jrides.models.map.rideoverview.TrainVisualFactory; +import com.jverbruggen.jrides.models.message.MessageFactory; +import com.jverbruggen.jrides.models.properties.frame.factory.FrameFactory; +import com.jverbruggen.jrides.models.ride.factory.*; +import com.jverbruggen.jrides.models.ride.section.provider.SectionProvider; +import com.jverbruggen.jrides.nms.NMSHandler; +import com.jverbruggen.jrides.nms.NMSHandlerFactory; +import com.jverbruggen.jrides.packets.PacketSender; +import com.jverbruggen.jrides.packets.PacketSenderFactory; +import com.jverbruggen.jrides.packets.listener.VirtualEntityPacketListener; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.RideCounterManager; +import com.jverbruggen.jrides.state.ride.coaster.CoasterLoader; +import com.jverbruggen.jrides.state.ride.flatride.AnimationLoader; +import com.jverbruggen.jrides.state.ride.menu.RideOverviewMenuButtonFactory; +import com.jverbruggen.jrides.state.ride.menu.RideOverviewMenuFactory; +import com.jverbruggen.jrides.state.viewport.ViewportManager; +import com.jverbruggen.jrides.state.viewport.ViewportManagerFactory; +import com.jverbruggen.jrides.state.player.PlayerManager; +import com.jverbruggen.jrides.state.ride.RideManager; +import me.m56738.smoothcoasters.api.SmoothCoastersAPI; +import org.bukkit.Bukkit; +import org.bukkit.plugin.PluginManager; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class ServiceProviderConfigurator { + public static void configure(JavaPlugin plugin){ + File dataFolder = plugin.getDataFolder(); + + Logger logger = plugin.getLogger(); + logger.setLevel(Level.CONFIG); + ServiceProvider.register(Logger.class, logger); + ServiceProvider.register(JRidesLogger.class, new JRidesLogger(logger, false, true)); + + ServiceProvider.register(PluginManager.class, Bukkit.getPluginManager()); + ServiceProvider.register(ConfigManager.class, new ConfigManager(plugin)); + ServiceProvider.register(LanguageFile.class, new LanguageFile()); + + ServiceProvider.register(MenuSessionManager.class, new MenuSessionManager()); + ServiceProvider.register(MessageAgentManager.class, new MessageAgentManager()); + ServiceProvider.register(RideCounterManager.class, new RideCounterManager()); + ServiceProvider.register(ControlModeFactory.class, new ControlModeFactory()); + ServiceProvider.register(RideControllerFactory.class, new RideControllerFactory()); + ServiceProvider.register(RideControlButtonFactory.class, new RideControlButtonFactory()); + ServiceProvider.register(RideControlMenuFactory.class, new RideControlMenuFactory()); + ServiceProvider.register(SectionProvider.class, new SectionProvider()); + ServiceProvider.register(ButtonUpdateController.class, new ButtonUpdateController()); + ServiceProvider.register(ProtocolManager.class, ProtocolLibrary.getProtocolManager()); + ServiceProvider.register(EntityIdFactory.class, new EntityIdFactory(1_500_000, Integer.MAX_VALUE)); + ServiceProvider.register(PacketSender.class, PacketSenderFactory.getPacketSender()); + ServiceProvider.register(NMSHandler.class, NMSHandlerFactory.getNMSHandler()); + ServiceProvider.register(ViewportManager.class, new ViewportManagerFactory().createViewportManager(true)); + ServiceProvider.register(FrameFactory.class, new FrameFactory()); + ServiceProvider.register(SmoothAnimation.class, new SmoothCoastersSmoothAnimation(new SmoothCoastersAPI(plugin))); + ServiceProvider.register(TriggerConfigFactory.class, new TriggerConfigFactory()); + ServiceProvider.register(EffectTriggerFactory.class, new EffectTriggerFactory()); + ServiceProvider.register(MessageFactory.class, new MessageFactory()); + ServiceProvider.register(PlayerManager.class, new PlayerManager()); + ServiceProvider.register(SeatFactory.class, new SeatFactory()); + ServiceProvider.register(TrainFactory.class, new TrainFactory()); + ServiceProvider.register(CartMovementFactory.class, new CartMovementFactory()); + ServiceProvider.register(TrackBehaviourFactory.class, new TrackBehaviourFactory()); + ServiceProvider.register(CoasterLoader.class, new CoasterLoader(dataFolder)); + ServiceProvider.register(FlatRideFactory.class, new FlatRideFactory()); + ServiceProvider.register(RideManager.class, new RideManager()); + ServiceProvider.register(SectionVisualFactory.class, new SectionVisualFactory()); + ServiceProvider.register(TrainVisualFactory.class, new TrainVisualFactory()); + ServiceProvider.register(RideOverviewMapFactory.class, new RideOverviewMapFactory()); + ServiceProvider.register(RideCounterMapFactory.class, new RideCounterMapFactory()); + ServiceProvider.register(RideOverviewMenuButtonFactory.class, new RideOverviewMenuButtonFactory()); + ServiceProvider.register(RideOverviewMenuFactory.class, new RideOverviewMenuFactory()); + ServiceProvider.register(AnimationLoader.class, new AnimationLoader(dataFolder)); + + ServiceProvider.register(VirtualEntityPacketListener.class, new VirtualEntityPacketListener()); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/state/player/BukkitPlayerJoinEventListener.java b/src/main/java/com/jverbruggen/jrides/state/player/BukkitPlayerJoinEventListener.java new file mode 100644 index 00000000..fb0ada3c --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/state/player/BukkitPlayerJoinEventListener.java @@ -0,0 +1,31 @@ +package com.jverbruggen.jrides.state.player; + +import com.jverbruggen.jrides.event.player.PlayerJoinEvent; +import com.jverbruggen.jrides.event.player.PlayerQuitEvent; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.player.PlayerManager; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; + +public class BukkitPlayerJoinEventListener implements Listener { + private final PlayerManager playerManager; + + public BukkitPlayerJoinEventListener() { + this.playerManager = ServiceProvider.getSingleton(PlayerManager.class); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent bukkitEvent){ + Player player = playerManager.registerPlayer(bukkitEvent.getPlayer()); + PlayerJoinEvent.send(player); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerQuit(org.bukkit.event.player.PlayerJoinEvent bukkitEvent){ + // TODO: Is this correct??? + Player player = playerManager.registerPlayer(bukkitEvent.getPlayer()); + PlayerQuitEvent.send(player); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/state/player/PlayerManager.java b/src/main/java/com/jverbruggen/jrides/state/player/PlayerManager.java new file mode 100644 index 00000000..85cf43af --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/state/player/PlayerManager.java @@ -0,0 +1,76 @@ +package com.jverbruggen.jrides.state.player; + +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.ride.count.RideCounterRecordCollection; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.RideCounterManager; +import org.bukkit.Bukkit; + +import java.util.*; + +public class PlayerManager { + private final HashMap players; + private final List operators; + private final RideCounterManager rideCounterManager; + + public PlayerManager(){ + players = new HashMap<>(); + operators = new ArrayList<>(); + rideCounterManager = ServiceProvider.getSingleton(RideCounterManager.class); + } + + public Player registerPlayer(org.bukkit.entity.Player bukkitPlayer){ + RideCounterRecordCollection rideCounters = rideCounterManager.getCollection(bukkitPlayer.getUniqueId().toString()); + + Player player = new Player(bukkitPlayer, rideCounters); + + UUID uuid = bukkitPlayer.getUniqueId(); + players.put(uuid, player); + return player; + } + + public Player getPlayer(org.bukkit.entity.Player bukkitPlayer){ + UUID uuid = bukkitPlayer.getUniqueId(); + if(!players.containsKey(uuid)){ + return registerPlayer(bukkitPlayer); + } + return players.get(uuid); + } + + public void removePlayer(org.bukkit.entity.Player bukkitPlayer){ + UUID uuid = bukkitPlayer.getUniqueId(); + if(!players.containsKey(uuid)){ + return; + } + Player player = players.remove(uuid); + if(isOperator(player)) unregisterOperator(player); + } + + public Player fromIdentifier(String playerIdentifier){ + UUID uuid = UUID.fromString(playerIdentifier); + org.bukkit.entity.Player bukkitPlayer = Bukkit.getPlayer(uuid); + if(bukkitPlayer == null) return null; + + return getPlayer(bukkitPlayer); + } + + public Collection getPlayers(){ + return players.values(); + } + + public void registerOperator(Player player){ + operators.add(player); + } + + public void unregisterOperator(Player player){ + operators.remove(player); + } + + public boolean isOperator(Player player){ + return operators.contains(player); + } + + public List getOperators(){ + return operators; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/state/player/PlayerManagerListener.java b/src/main/java/com/jverbruggen/jrides/state/player/PlayerManagerListener.java new file mode 100644 index 00000000..7865cf5d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/state/player/PlayerManagerListener.java @@ -0,0 +1,18 @@ +package com.jverbruggen.jrides.state.player; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerQuitEvent; + +public class PlayerManagerListener implements Listener { + private PlayerManager playerManager; + + public PlayerManagerListener(PlayerManager playerManager) { + this.playerManager = playerManager; + } + + @EventHandler + public void onQuit(PlayerQuitEvent event){ + playerManager.removePlayer(event.getPlayer()); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/state/ride/RideCounterManager.java b/src/main/java/com/jverbruggen/jrides/state/ride/RideCounterManager.java new file mode 100644 index 00000000..dad303fe --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/state/ride/RideCounterManager.java @@ -0,0 +1,139 @@ +package com.jverbruggen.jrides.state.ride; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.api.JRidesPlayer; +import com.jverbruggen.jrides.config.ConfigManager; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.language.LanguageFileTag; +import com.jverbruggen.jrides.models.ride.Ride; +import com.jverbruggen.jrides.models.ride.count.RideCounterRecord; +import com.jverbruggen.jrides.models.ride.count.RideCounterRecordCollection; +import com.jverbruggen.jrides.models.ride.count.RideCounterRecordRideCollection; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.util.HashMap; +import java.util.Map; + +public class RideCounterManager { + private static final String ROOT_CONFIG_KEY = "counters"; + + private final LanguageFile languageFile; + private final Map cachedPlayerCollections; + private final Map cachedRideCollections; + + public RideCounterManager() { + this.languageFile = ServiceProvider.getSingleton(LanguageFile.class); + this.cachedPlayerCollections = new HashMap<>(); + this.cachedRideCollections = new HashMap<>(); + } + + public void sendRideCounterUpdateMessage(JRidesPlayer player, RideCounterRecord record){ + languageFile.sendMultilineMessage(player, LanguageFileField.NOTIFICATION_RIDE_COUNTER_UPDATE, + builder -> builder + .add(LanguageFileTag.rideCount, String.valueOf(record.getRideCount())) + .add(LanguageFileTag.rideDisplayName, record.getRide().getDisplayName())); + } + + public RideCounterRecordCollection getCollection(String playerIdentifier){ + RideCounterRecordCollection collection = getCachedPlayerCollection(playerIdentifier); + if(collection != null) + return collection; + + collection = loadFromFile(playerIdentifier); + cachedPlayerCollections.put(playerIdentifier, collection); + return collection; + } + + public RideCounterRecordRideCollection getCollectionRideBound(String rideIdentifier){ + RideCounterRecordRideCollection collection = getCachedRideCollection(rideIdentifier); + if(collection != null) + return collection; + + collection = loadForRideFromFile(rideIdentifier); + cachedRideCollections.put(rideIdentifier, collection); + return collection; + } + + public void saveAndUnloadAll(){ + for(Map.Entry entry : cachedPlayerCollections.entrySet()){ + saveToFile(entry.getKey(), entry.getValue()); + } + + cachedPlayerCollections.clear(); + } + + public void saveAndUnload(String playerIdentifier){ + RideCounterRecordCollection rideCounterRecordCollection = getCachedPlayerCollection(playerIdentifier); + if(saveToFile(playerIdentifier, rideCounterRecordCollection)){ + removeCached(playerIdentifier); + } + } + private RideCounterRecordCollection getCachedPlayerCollection(String playerIdentifier){ + return cachedPlayerCollections.get(playerIdentifier); + } + + private RideCounterRecordRideCollection getCachedRideCollection(String rideIdentifier){ + return cachedRideCollections.get(rideIdentifier); + } + + private void removeCached(String playerIdentifier){ + cachedPlayerCollections.remove(playerIdentifier); + } + + private String getRideCounterFile(String playerIdentifier){ + return "ridecounters/player/" + playerIdentifier + ".yml"; + } + + private String getRideCounterFileRide(String rideIdentifier){ + return "ridecounters/ride/" + rideIdentifier + ".yml"; + } + + private RideCounterRecordCollection loadFromFile(String playerIdentifier){ + String fileName = getRideCounterFile(playerIdentifier); + YamlConfiguration configuration = ServiceProvider.getSingleton(ConfigManager.class).getYamlConfiguration(fileName); + + if(configuration == null || !configuration.contains(ROOT_CONFIG_KEY)) + return new RideCounterRecordCollection(playerIdentifier); + + return (RideCounterRecordCollection) configuration.get(ROOT_CONFIG_KEY); + } + + private RideCounterRecordRideCollection loadForRideFromFile(String rideIdentifier){ + String fileName = getRideCounterFileRide(rideIdentifier); + YamlConfiguration configuration = ServiceProvider.getSingleton(ConfigManager.class).getYamlConfiguration(fileName); + + if(configuration == null || !configuration.contains(ROOT_CONFIG_KEY)){ + RideHandle rideHandle = ServiceProvider.getSingleton(RideManager.class).getRideHandle(rideIdentifier); + return new RideCounterRecordRideCollection(rideHandle); + } + + return (RideCounterRecordRideCollection) configuration.get(ROOT_CONFIG_KEY); + } + + public boolean saveToFile(String playerIdentifier, RideCounterRecordCollection rideCounterRecordCollection){ + if(rideCounterRecordCollection == null) return false; + + String fileName = getRideCounterFile(playerIdentifier); + saveToYamlConfiguration(fileName, rideCounterRecordCollection); + return true; + } + + public boolean saveToRideFile(String rideIdentifier, RideCounterRecordRideCollection rideCounterRecordRideCollection){ + if(rideCounterRecordRideCollection == null) return false; + + String fileName = getRideCounterFileRide(rideIdentifier); + saveToYamlConfiguration(fileName, rideCounterRecordRideCollection); + return true; + } + + private void saveToYamlConfiguration(String fileName, Object object){ + ConfigManager configManager = ServiceProvider.getSingleton(ConfigManager.class); + + YamlConfiguration configuration = configManager.getOrCreateConfiguration(fileName); + configuration.set(ROOT_CONFIG_KEY, object); + + configManager.saveConfig(configuration, fileName); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/state/ride/RideManager.java b/src/main/java/com/jverbruggen/jrides/state/ride/RideManager.java new file mode 100644 index 00000000..8d9c3d10 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/state/ride/RideManager.java @@ -0,0 +1,143 @@ +package com.jverbruggen.jrides.state.ride; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.animator.flatride.factory.FlatRideFactory; +import com.jverbruggen.jrides.config.ConfigManager; +import com.jverbruggen.jrides.config.coaster.CoasterConfig; +import com.jverbruggen.jrides.config.flatride.FlatRideConfig; +import com.jverbruggen.jrides.config.ride.RidesConfig; +import com.jverbruggen.jrides.config.ride.RidesConfigObject; +import com.jverbruggen.jrides.config.ride.RideState; +import com.jverbruggen.jrides.event.ride.RideInitializedEvent; +import com.jverbruggen.jrides.exception.CoasterLoadException; +import com.jverbruggen.jrides.logging.JRidesLogger; +import com.jverbruggen.jrides.models.properties.Speed; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.coaster.CoasterLoader; +import org.bukkit.Bukkit; +import org.bukkit.World; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; + +public class RideManager { + private final JRidesLogger logger; + private final List rideHandles; + private final ConfigManager configManager; + private final CoasterLoader coasterLoader; + private final FlatRideFactory flatRideFactory; + private final List rideIdentifiers; + + public RideManager() { + this.logger = ServiceProvider.getSingleton(JRidesLogger.class); + this.rideHandles = new ArrayList<>(); + this.configManager = ServiceProvider.getSingleton(ConfigManager.class); + this.coasterLoader = ServiceProvider.getSingleton(CoasterLoader.class); + this.flatRideFactory = ServiceProvider.getSingleton(FlatRideFactory.class); + this.rideIdentifiers = new ArrayList<>(); + } + + public void addRideHandle(RideHandle rideHandle){ + rideHandles.add(rideHandle); + } + + public List getRideIdentifiers() { + return rideIdentifiers; + } + + public List getRideHandles() { + return rideHandles; + } + + public @Nullable RideHandle getRideHandle(String identifier){ + return this.rideHandles + .stream() + .filter(ch -> ch.getRide().getIdentifier().equalsIgnoreCase(identifier)) + .findFirst() + .orElse(null); + } + + public void initAllRides(World world){ + RidesConfig ridesConfig = configManager.getRideConfig(); + if(ridesConfig == null) return; + + List ridesConfigObjects = ridesConfig.getRides(); + + for (RidesConfigObject ridesConfigObject : ridesConfigObjects) { + String rideIdentifier = ridesConfigObject.getIdentifier(); + String rideType = ridesConfigObject.getType(); + + if(rideIdentifiers.contains(rideIdentifier)) throw new RuntimeException("Ride " + rideIdentifier + " identifier already exists!"); + rideIdentifiers.add(rideIdentifier); + + logger.info("Initialising ride " + rideIdentifier + " with type " + rideType); + + if(rideType.equals("coaster")) { + try { + loadCoaster(world, rideIdentifier); + } catch (CoasterLoadException e) { + JRidesPlugin.getLogger().severe("Could not load coaster " + rideIdentifier); + } + }else if(rideType.equals("flatride")){ + loadFlatRide(world, rideIdentifier); + }else throw new RuntimeException("Ride type unknown: " + rideType); + } + + start(); + RideInitializedEvent.send(); + } + + public void unloadAllRides(){ + getRideHandles().forEach(r -> r.unload(true)); + } + + private void loadCoaster(World world, String rideIdentifier) throws CoasterLoadException { + RideState rideState = RideState.loadCoasterState(rideIdentifier); + if(!rideState.shouldLoadRide()){ + logger.warning("Not loading ride " + rideIdentifier); + return; + } + + CoasterConfig coasterConfig = configManager.getCoasterConfig(rideIdentifier); + if(coasterConfig == null) { + logger.warning("Coaster '" + rideIdentifier + "' has no config file present, not loading"); + return; + } + + CoasterHandle rideHandle = coasterLoader.loadCoaster(coasterConfig, rideIdentifier, rideState, world); + if(rideHandle != null) this.addRideHandle(rideHandle); + } + + private void loadFlatRide(World world, String rideIdentifier){ + RideState rideState = RideState.loadFlatrideState(rideIdentifier); + if(!rideState.shouldLoadRide()){ + logger.warning("Not loading flatride " + rideIdentifier); + return; + } + + FlatRideConfig flatRideConfig = configManager.getFlatRideConfig(rideIdentifier); + if(flatRideConfig == null) { + logger.warning("Flatride '" + rideIdentifier + "' has no config file present, not loading"); + return; + } + + RideHandle rideHandle = flatRideFactory.createFromConfig(rideIdentifier, world, rideState, flatRideConfig); +// RideHandle rideHandle = flatRideFactory.createSimpleFlatRide(rideIdentifier, world, rideState); + if(rideHandle != null) this.addRideHandle(rideHandle); + } + + private void start(){ + Bukkit.getScheduler().runTaskTimer(JRidesPlugin.getBukkitPlugin(), this::tick, 1L, 1L); + } + + private void tick(){ + for(RideHandle rideHandle : rideHandles){ + rideHandle.tick(); + } + + Speed.incrementFractionalSpeedCounter(); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/state/ride/SoftEjector.java b/src/main/java/com/jverbruggen/jrides/state/ride/SoftEjector.java new file mode 100644 index 00000000..92fd8702 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/state/ride/SoftEjector.java @@ -0,0 +1,49 @@ +package com.jverbruggen.jrides.state.ride; + +import com.jverbruggen.jrides.models.entity.Player; +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; + +import java.util.*; + +public class SoftEjector { + public static int ejectInterval = 2*20; + public static List removeList = new ArrayList<>(); + public static Map playerTimers = new HashMap<>(); + + public static void startClock(JavaPlugin plugin){ + Bukkit.getScheduler().runTaskTimer(plugin, SoftEjector::tick, 1L, 1L); + } + + public static void tick(){ + if(playerTimers.size() == 0) return; + + for(Map.Entry entry : playerTimers.entrySet()){ + int timerState = entry.getValue(); + UUID uuid = entry.getKey(); + timerState -= 1; + if(timerState <= 0){ + removeList.add(uuid); + }else{ + playerTimers.put(uuid, timerState); + } + } + + for(UUID uuid : removeList){ + playerTimers.remove(uuid); + } + removeList.clear(); + } + + public static void addTimer(Player player){ + playerTimers.put(player.getBukkitPlayer().getUniqueId(), ejectInterval); + } + + public static boolean hasTimer(Player player){ + return playerTimers.containsKey(player.getBukkitPlayer().getUniqueId()); + } + + public static void removeTimer(Player player){ + playerTimers.remove(player.getBukkitPlayer().getUniqueId()); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/state/ride/coaster/CoasterLoader.java b/src/main/java/com/jverbruggen/jrides/state/ride/coaster/CoasterLoader.java new file mode 100644 index 00000000..c82ce96a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/state/ride/coaster/CoasterLoader.java @@ -0,0 +1,221 @@ +package com.jverbruggen.jrides.state.ride.coaster; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.animator.coaster.CoasterHandle; +import com.jverbruggen.jrides.animator.coaster.NoLimitsExportPositionRecord; +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.config.ConfigManager; +import com.jverbruggen.jrides.config.coaster.CoasterConfig; +import com.jverbruggen.jrides.config.coaster.objects.SoundsConfig; +import com.jverbruggen.jrides.config.coaster.objects.TrackConfig; +import com.jverbruggen.jrides.config.ride.RideState; +import com.jverbruggen.jrides.control.controller.RideController; +import com.jverbruggen.jrides.control.controller.RideControllerFactory; +import com.jverbruggen.jrides.control.uiinterface.menu.RideControlMenuFactory; +import com.jverbruggen.jrides.effect.EffectTriggerCollection; +import com.jverbruggen.jrides.effect.EffectTriggerFactory; +import com.jverbruggen.jrides.effect.handle.cart.CartEffectTriggerHandle; +import com.jverbruggen.jrides.effect.handle.train.TrainEffectTriggerHandle; +import com.jverbruggen.jrides.exception.CoasterLoadException; +import com.jverbruggen.jrides.exception.NoTrackSpecifiedException; +import com.jverbruggen.jrides.items.ItemStackFactory; +import com.jverbruggen.jrides.logging.JRidesLogger; +import com.jverbruggen.jrides.models.menu.Menu; +import com.jverbruggen.jrides.models.properties.PlayerLocation; +import com.jverbruggen.jrides.models.properties.frame.Frame; +import com.jverbruggen.jrides.models.properties.frame.SimpleFrame; +import com.jverbruggen.jrides.models.ride.Ride; +import com.jverbruggen.jrides.models.ride.coaster.SimpleCoaster; +import com.jverbruggen.jrides.models.ride.coaster.track.Track; +import com.jverbruggen.jrides.models.ride.coaster.train.Train; +import com.jverbruggen.jrides.models.ride.factory.ConfigAdvancedSplineTrackFactory; +import com.jverbruggen.jrides.models.ride.factory.TrackFactory; +import com.jverbruggen.jrides.models.ride.factory.TrainFactory; +import com.jverbruggen.jrides.models.ride.factory.track.TrackDescription; +import com.jverbruggen.jrides.models.ride.factory.track.TrackType; +import com.jverbruggen.jrides.models.ride.factory.train.TrainCreationResult; +import com.jverbruggen.jrides.models.ride.section.provider.SectionProvider; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.World; +import org.bukkit.inventory.ItemStack; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class CoasterLoader { + private final JRidesLogger logger; + private final File dataFolder; + private final ConfigManager configManager; + private final TrainFactory trainFactory; + private final EffectTriggerFactory effectTriggerFactory; + private final RideControllerFactory rideControllerFactory; + private final RideControlMenuFactory rideControlMenuFactory; + private final List rideOverviewMapIds; + + public CoasterLoader(File dataFolder) { + this.logger = ServiceProvider.getSingleton(JRidesLogger.class); + this.dataFolder = dataFolder; + this.configManager = ServiceProvider.getSingleton(ConfigManager.class); + this.trainFactory = ServiceProvider.getSingleton(TrainFactory.class); + this.effectTriggerFactory = ServiceProvider.getSingleton(EffectTriggerFactory.class); + this.rideControllerFactory = ServiceProvider.getSingleton(RideControllerFactory.class); + this.rideControlMenuFactory = ServiceProvider.getSingleton(RideControlMenuFactory.class); + this.rideOverviewMapIds = new ArrayList<>(); + } + + public CoasterHandle loadCoaster(CoasterConfig coasterConfig, String rideIdentifier, RideState rideState, World world) throws CoasterLoadException { + CoasterHandle coasterHandle = null; + boolean tryAgain = true; + int tries = 5; + + while(tryAgain && tries > 0){ + tryAgain = false; + tries--; + try{ + coasterHandle = loadNormally(coasterConfig, rideIdentifier, rideState, world); + }catch (NoTrackSpecifiedException exception){ + if(rideState.isInactive()) throw exception; + rideState.setInactive(); + tryAgain = true; + }catch (CoasterLoadException exception){ + JRidesPlugin.getLogger().severe("An error occured while loading " + rideIdentifier + ": " + exception.getMessage()); + } + } + + return coasterHandle; + } + + public CoasterHandle loadNormally(CoasterConfig coasterConfig, String rideIdentifier, RideState rideState, World world) throws CoasterLoadException { + String displayName = coasterConfig.getDisplayName(); + List displayDescription = coasterConfig.getDisplayDescription(); + + ItemStack displayItem = ItemStackFactory.getCoasterStackFromConfig(coasterConfig.getDisplayItem()); + + PlayerLocation customEjectLocation = coasterConfig.getCustomEjectLocation(); + PlayerLocation warpLocation = coasterConfig.getWarpLocation(); + boolean canExitDuringRide = coasterConfig.canExitDuringRide(); + Ride ride = new SimpleCoaster(rideIdentifier, displayName, displayDescription, displayItem, warpLocation, canExitDuringRide); + + // Initialize Handle + int rideOverviewMapId = coasterConfig.getRideOverviewMapId(); + if(!rideOverviewMapIds.contains(rideOverviewMapId)) + rideOverviewMapIds.add(rideOverviewMapId); + else throw new CoasterLoadException("When loading " + rideIdentifier + ": RideOverviewMap id=" + rideOverviewMapId + " was already taken by another coaster."); + + SoundsConfig sounds = coasterConfig.getSoundsConfig(); + + CoasterHandle coasterHandle = new CoasterHandle(ride, world, sounds, customEjectLocation, rideOverviewMapId, !rideState.isInactive(), + coasterConfig.getDragConstant(), coasterConfig.getGravityConstant(), coasterConfig.getRideCounterMapConfigs()); + + coasterConfig.getInteractionEntities().spawnEntities(coasterHandle); + + // Initialize Track + if(!rideState.isInactive()){ + TrackConfig trackConfig = coasterConfig.getTrack(); + if(!trackConfig.isCorrectlyLoaded()){ + throw new NoTrackSpecifiedException("Not correctly configured in coaster config"); + } + List offset = trackConfig.getPosition(); + + float offsetX = offset.get(0); + float offsetY = offset.get(1); + float offsetZ = offset.get(2); + Track track = loadCoasterTrackFromConfig(coasterHandle, coasterConfig, offsetX, offsetY, offsetZ); + if(track == null){ + logger.severe("Track was null, so coaster " + rideIdentifier + " could not be loaded"); + throw new NoTrackSpecifiedException(); + } + coasterHandle.setTrack(track); + + EffectTriggerCollection effectTriggerCollection = effectTriggerFactory.getTrainEffectTriggers(rideIdentifier, track); + coasterHandle.setTrainEffectTriggerCollection(effectTriggerCollection); + EffectTriggerCollection cartEffectTriggerCollection = effectTriggerFactory.getCartEffectTriggers(rideIdentifier, track); + coasterHandle.setCartEffectTriggerCollection(cartEffectTriggerCollection); + + SectionProvider sectionProvider = new SectionProvider(); + int trainCount = coasterConfig.getVehicles().getTrains(); + + TrainCreationResult trainCreationResult = createTrains(coasterHandle, track, coasterConfig, sectionProvider, rideIdentifier, trainCount); + List trainHandles = trainCreationResult.output(); + if(!trainCreationResult.success()){ + coasterHandle.unload(false); + trainFactory.unloadAll(trainHandles); + throw new CoasterLoadException(); + } + coasterHandle.setTrains(trainHandles); + + RideController rideController = rideControllerFactory.createCoasterController(coasterHandle, coasterConfig.getControllerConfig()); + Menu rideControlMenu = rideControlMenuFactory.getRideControlMenu(rideController, coasterConfig.getControllerConfig()); + coasterHandle.setRideController(rideController, rideControlMenu); + } + + coasterHandle.setState(rideState); + + return coasterHandle; + } + + private TrainCreationResult createTrains(CoasterHandle coasterHandle, Track track, CoasterConfig coasterConfig, SectionProvider sectionProvider, String rideIdentifier, int count) { + List trains = new ArrayList<>(); + for(int i = 0; i < count; i++){ + String trainName = rideIdentifier + ":train_" + (i+1); + TrainHandle trainHandle = createTrain(coasterHandle, track, coasterConfig, sectionProvider, trainName); + if(trainHandle != null) + trains.add(trainHandle); + else return new TrainCreationResult(trains, false); + } + return new TrainCreationResult(trains, true); + } + + private Track loadCoasterTrackFromConfig(CoasterHandle coasterHandle, CoasterConfig coasterConfig, float offsetX, float offsetY, float offsetZ){ + List trackIdentifiers = coasterConfig.getTrack().getParts(); + List trackDescriptions = trackIdentifiers.stream() + .map(identifier -> loadTrackSegmentFromConfig(identifier, coasterHandle, coasterConfig, offsetX, offsetY, offsetZ)) + .collect(Collectors.toList()); + + TrackFactory trackFactory = new ConfigAdvancedSplineTrackFactory(coasterHandle, coasterConfig, trackDescriptions); + return trackFactory.createTrack(); + } + + private TrainHandle createTrain(CoasterHandle coasterHandle, Track track, CoasterConfig coasterConfig, SectionProvider sectionProvider, String trainIdentifier){ + Train train = trainFactory.createEquallyDistributedTrain(coasterHandle, track, coasterConfig, trainIdentifier); + if(train == null) return null; + + return new TrainHandle(sectionProvider, train, track); + } + + private TrackDescription loadTrackSegmentFromConfig(String trackIdentifier, CoasterHandle coasterHandle, CoasterConfig coasterConfig, float offsetX, float offsetY, float offsetZ){ + Ride ride = coasterHandle.getRide(); + String rideIdentifier = ride.getIdentifier(); + String configFileName = configManager.getCoasterFolder(rideIdentifier) + "/track/" + rideIdentifier + "." + trackIdentifier + ".csv"; + File configFile = new File(dataFolder, configFileName); + Path pathToConfigFile = configFile.toPath(); + List positions = new ArrayList<>(); + + try(BufferedReader br = Files.newBufferedReader(pathToConfigFile, StandardCharsets.UTF_8)){ + String line = br.readLine(); // Skip header line + line = br.readLine(); + int index = 0; + while(line != null){ + String[] attributes = line.split("\t"); + NoLimitsExportPositionRecord record = NoLimitsExportPositionRecord.createFromCSVAttributes(attributes, index, offsetX, offsetY, offsetZ); + positions.add(record); + + line = br.readLine(); + index++; + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + + Frame startFrame = new SimpleFrame(0); + Frame endFrame = new SimpleFrame(positions.size()-1); + return new TrackDescription(trackIdentifier, positions, TrackType.TRACK, startFrame, endFrame); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/state/ride/flatride/Animation.java b/src/main/java/com/jverbruggen/jrides/state/ride/flatride/Animation.java new file mode 100644 index 00000000..951b6fcc --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/state/ride/flatride/Animation.java @@ -0,0 +1,33 @@ +package com.jverbruggen.jrides.state.ride.flatride; + +import com.jverbruggen.jrides.animator.flatride.BlenderExportPositionRecord; +import com.jverbruggen.jrides.models.math.VectorQuaternionState; + +import java.util.ArrayList; +import java.util.List; + +public class Animation { + private final String target; + private final List frames; + + public Animation(String target) { + this.target = target; + this.frames = new ArrayList<>(); + } + + public String getTarget() { + return target; + } + + public void addPosition(BlenderExportPositionRecord rawPosition) { + frames.add(rawPosition); + } + + public List getFrames() { + return frames; + } + + public VectorQuaternionState getInitialPose(){ + return frames.get(0).toVectorQuaternionState(); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/state/ride/flatride/AnimationHandle.java b/src/main/java/com/jverbruggen/jrides/state/ride/flatride/AnimationHandle.java new file mode 100644 index 00000000..b844121a --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/state/ride/flatride/AnimationHandle.java @@ -0,0 +1,56 @@ +package com.jverbruggen.jrides.state.ride.flatride; + +import com.jverbruggen.jrides.animator.flatride.BlenderExportPositionRecord; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; + +public class AnimationHandle { + private final HashMap animationHashMap; + + public AnimationHandle(){ + this.animationHashMap = new LinkedHashMap<>(); + } + + public Animation getAnimation(String animationIdentifier){ + if(!animationHashMap.containsKey(animationIdentifier)){ + String animationKeys = String.join(", ", animationHashMap.keySet()); + throw new RuntimeException("Animation with key '" + animationIdentifier + "' does not exist. Existing: " + animationKeys); + } + + return animationHashMap.get(animationIdentifier); + } + + public void putAnimation(Animation animation){ + String animationTarget = animation.getFrames().get(0).getObject(); + if (animationHashMap.containsKey(animationTarget)) { + throw new RuntimeException("AnimationHandle has defined animations for " + animationTarget + " more than once!"); + } + + animationHashMap.put(animationTarget, animation); + } + + public static AnimationHandle createAnimationHandle(List rawPositions){ + AnimationHandle animationHandle = new AnimationHandle(); + + Animation animation = null; + for(BlenderExportPositionRecord rawPosition : rawPositions){ + String rawPositionTarget = rawPosition.getObject(); + if(animation == null){ + animation = new Animation(rawPositionTarget); + }else if(!animation.getTarget().equalsIgnoreCase(rawPositionTarget)){ + animationHandle.putAnimation(animation); + animation = new Animation(rawPositionTarget); + } + + animation.addPosition(rawPosition); + } + + if(animation != null) + animationHandle.putAnimation(animation); + + return animationHandle; + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/state/ride/flatride/AnimationLoader.java b/src/main/java/com/jverbruggen/jrides/state/ride/flatride/AnimationLoader.java new file mode 100644 index 00000000..e77aa75b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/state/ride/flatride/AnimationLoader.java @@ -0,0 +1,63 @@ +package com.jverbruggen.jrides.state.ride.flatride; + +import com.jverbruggen.jrides.animator.flatride.BlenderExportPositionRecord; +import com.jverbruggen.jrides.animator.flatride.FlatRideHandle; +import com.jverbruggen.jrides.config.ConfigManager; +import com.jverbruggen.jrides.models.ride.Ride; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; + +public class AnimationLoader { + private final File dataFolder; + private final ConfigManager configManager; + private final HashMap cachedFlatRideAnimationHandles; + + public AnimationLoader(File dataFolder) { + this.dataFolder = dataFolder; + this.configManager = ServiceProvider.getSingleton(ConfigManager.class); + this.cachedFlatRideAnimationHandles = new LinkedHashMap<>(); + } + + public AnimationHandle loadFlatRideAnimation(String animationHandleIdentifier, FlatRideHandle flatRideHandle){ + if(cachedFlatRideAnimationHandles.containsKey(animationHandleIdentifier)) + return cachedFlatRideAnimationHandles.get(animationHandleIdentifier); + + Ride ride = flatRideHandle.getRide(); + String rideIdentifier = ride.getIdentifier(); + String configFileName = configManager.getFlatrideFolder(rideIdentifier) + "/animations/" + rideIdentifier + "." + animationHandleIdentifier + ".csv"; + File configFile = new File(dataFolder, configFileName); + Path pathToConfigFile = configFile.toPath(); + List positions = new ArrayList<>(); + + try(BufferedReader br = Files.newBufferedReader(pathToConfigFile, StandardCharsets.UTF_8)){ + String line = br.readLine(); // Skip header line + line = br.readLine(); + int index = 0; + while(line != null){ + String[] attributes = line.split(", "); + BlenderExportPositionRecord record = BlenderExportPositionRecord.createFromCSVAttributes(attributes); + positions.add(record); + + line = br.readLine(); + index++; + } + } catch (IOException ioe) { + ioe.printStackTrace(); + } + + AnimationHandle animationHandle = AnimationHandle.createAnimationHandle(positions); + cachedFlatRideAnimationHandles.put(animationHandleIdentifier, animationHandle); + + return animationHandle; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/state/ride/menu/RideMenuLoader.java b/src/main/java/com/jverbruggen/jrides/state/ride/menu/RideMenuLoader.java new file mode 100644 index 00000000..b82683cc --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/state/ride/menu/RideMenuLoader.java @@ -0,0 +1,22 @@ +package com.jverbruggen.jrides.state.ride.menu; + +import com.jverbruggen.jrides.event.ride.RideInitializedEvent; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import com.jverbruggen.jrides.state.ride.RideManager; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class RideMenuLoader implements Listener { + private final RideOverviewMenuFactory rideOverviewMenuFactory; + private final RideManager rideManager; + + public RideMenuLoader(){ + rideOverviewMenuFactory = ServiceProvider.getSingleton(RideOverviewMenuFactory.class); + rideManager = ServiceProvider.getSingleton(RideManager.class); + } + + @EventHandler + public void onRidesInitialized(RideInitializedEvent event){ + rideOverviewMenuFactory.createRideOverviewMenu(rideManager.getRideHandles()); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/state/ride/menu/RideOverviewMenuButtonFactory.java b/src/main/java/com/jverbruggen/jrides/state/ride/menu/RideOverviewMenuButtonFactory.java new file mode 100644 index 00000000..a8a7023b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/state/ride/menu/RideOverviewMenuButtonFactory.java @@ -0,0 +1,65 @@ +package com.jverbruggen.jrides.state.ride.menu; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.control.uiinterface.menu.button.action.RunnableButtonAction; +import com.jverbruggen.jrides.control.uiinterface.menu.button.common.StatefulButtonVisual; +import com.jverbruggen.jrides.control.uiinterface.menu.button.common.StaticButtonVisual; +import com.jverbruggen.jrides.items.ItemStackFactory; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.menu.ButtonVisual; +import com.jverbruggen.jrides.models.menu.MenuButton; +import com.jverbruggen.jrides.models.menu.SimpleMenuButton; +import com.jverbruggen.jrides.models.ride.state.OpenState; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.*; + +public class RideOverviewMenuButtonFactory { + private final LanguageFile languageFile; + + public RideOverviewMenuButtonFactory() { + this.languageFile = ServiceProvider.getSingleton(LanguageFile.class); + } + + public MenuButton createRideStatusButton(RideHandle rideHandle, int slot){ + HashMap options = new HashMap<>(); + ItemStack displayItem = rideHandle.getRide().getDisplayItem(); + if(displayItem == null) displayItem = new ItemStack(Material.STONE, 1); + + List lore = rideHandle.getRide().getDisplayDescription(); + List openLore = new ArrayList<>(lore); + List closedLore = new ArrayList<>(lore); + List maintenanceLore = new ArrayList<>(lore); + + openLore.add(""); + openLore.add(ChatColor.GREEN + languageFile.get(LanguageFileField.MENU_RIDE_OVERVIEW_STATUS_OPEN)); + closedLore.add(""); + closedLore.add(ChatColor.RED + languageFile.get(LanguageFileField.MENU_RIDE_OVERVIEW_STATUS_CLOSED)); + maintenanceLore.add(""); + maintenanceLore.add(ChatColor.DARK_GRAY + languageFile.get(LanguageFileField.MENU_RIDE_OVERVIEW_STATUS_MAINTENANCE)); + + ButtonVisual openVisual = new StaticButtonVisual(displayItem, ChatColor.GOLD, rideHandle.getRide().getDisplayName(), openLore); + ButtonVisual closedVisual = new StaticButtonVisual(displayItem, ChatColor.RED, rideHandle.getRide().getDisplayName(), closedLore); + ButtonVisual maintenanceVisual = new StaticButtonVisual(displayItem, ChatColor.GRAY, rideHandle.getRide().getDisplayName(), maintenanceLore); + + options.put(OpenState.OPEN, openVisual); + options.put(OpenState.CLOSED, closedVisual); + options.put(OpenState.TRANSITION_TO_OPEN, closedVisual); + options.put(OpenState.TRANSITION_TO_CLOSE, closedVisual); + options.put(OpenState.MAINTENANCE, maintenanceVisual); + options.put(OpenState.INACTIVE, maintenanceVisual); + + OpenState current = rideHandle.getState().getOpenState(); + if(current == null) current = OpenState.MAINTENANCE; + + return new SimpleMenuButton( + new StatefulButtonVisual<>(() -> rideHandle.getState().getOpenState(), options, current), + slot, + new RunnableButtonAction(p -> p.teleport(rideHandle.getRide().getWarpLocation())) + ); + } +} \ No newline at end of file diff --git a/src/main/java/com/jverbruggen/jrides/state/ride/menu/RideOverviewMenuFactory.java b/src/main/java/com/jverbruggen/jrides/state/ride/menu/RideOverviewMenuFactory.java new file mode 100644 index 00000000..d05f471d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/state/ride/menu/RideOverviewMenuFactory.java @@ -0,0 +1,45 @@ +package com.jverbruggen.jrides.state.ride.menu; + +import com.jverbruggen.jrides.animator.RideHandle; +import com.jverbruggen.jrides.language.LanguageFile; +import com.jverbruggen.jrides.language.LanguageFileField; +import com.jverbruggen.jrides.models.menu.Menu; +import com.jverbruggen.jrides.models.menu.SimpleMenu; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; + +import java.util.List; + +public class RideOverviewMenuFactory { + private final LanguageFile languageFile; + private final RideOverviewMenuButtonFactory rideOverviewMenuButtonFactory; + private Menu rideOverviewMenu; + + public RideOverviewMenuFactory() { + this.languageFile = ServiceProvider.getSingleton(LanguageFile.class); + this.rideOverviewMenuButtonFactory = ServiceProvider.getSingleton(RideOverviewMenuButtonFactory.class); + this.rideOverviewMenu = null; + } + + public Menu createRideOverviewMenu(List rideHandles){ + int count = rideHandles.size(); + if(count > 9*6) + // TODO: Large quantity of rides in menu support with pages + throw new RuntimeException("Menus for a large quantity of rides is not yet supported."); + + SimpleMenu rideOverviewMenu = new SimpleMenu(3, languageFile.get(LanguageFileField.MENU_RIDE_OVERVIEW_TITLE)); + for(int i = 0; i < count; i++){ + rideOverviewMenu.addButton(rideOverviewMenuButtonFactory.createRideStatusButton(rideHandles.get(i), i)); + } + + this.rideOverviewMenu = rideOverviewMenu; + + return rideOverviewMenu; + } + + public Menu getRideOverviewMenu(){ + if(this.rideOverviewMenu == null) + throw new RuntimeException("Ride overview menu was not created yet, probably due to a previous error"); + + return this.rideOverviewMenu; + } +} diff --git a/src/main/java/com/jverbruggen/jrides/state/viewport/GlobalViewportManager.java b/src/main/java/com/jverbruggen/jrides/state/viewport/GlobalViewportManager.java new file mode 100644 index 00000000..afdaabe9 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/state/viewport/GlobalViewportManager.java @@ -0,0 +1,167 @@ +package com.jverbruggen.jrides.state.viewport; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.models.entity.*; +import com.jverbruggen.jrides.models.entity.armorstand.VirtualArmorstand; +import com.jverbruggen.jrides.models.entity.armorstand.YawRotatedVirtualArmorstand; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.render.GlobalViewport; +import com.jverbruggen.jrides.packets.PacketSender; +import com.jverbruggen.jrides.packets.object.VirtualArmorstandConfiguration; +import org.bukkit.entity.EntityType; + +import java.util.HashMap; +import java.util.List; + +public class GlobalViewportManager implements ViewportManager { + private final GlobalViewport globalViewport; + private final PacketSender packetSender; + private final EntityIdFactory entityIdFactory; + private final HashMap entities; + + private final int renderDistance; + private final int renderChunkSize; + + public GlobalViewportManager(GlobalViewport globalViewport, PacketSender packetSender, EntityIdFactory entityIdFactory, + int renderDistance, int renderChunkSize) { + this.globalViewport = globalViewport; + this.packetSender = packetSender; + this.entityIdFactory = entityIdFactory; + this.entities = new HashMap<>(); + + this.renderDistance = renderDistance; + this.renderChunkSize = renderChunkSize; + } + + private void addEntity(VirtualEntity entity){ + entities.put(entity.getEntityId(), entity); + } + + private void removeEntity(int entityId){ + entities.remove(entityId); + } + + public VirtualEntity getEntity(int entityId){ + return entities.get(entityId); + } + + @Override + public int getRenderChunkSize() { + return renderChunkSize; + } + + @Override + public int getRenderDistance() { + return renderDistance; + } + + @Override + public void removeEntities(TrainHandle trainHandle) { + trainHandle.getTrain().despawn(); + flushDeadEntities(); + } + + @Override + public void removeEntities(List trainHandles) { + trainHandles.forEach(t -> t.getTrain().despawn()); + flushDeadEntities(); + } + + @Override + public void updateVisuals(Player player) { + updateVisuals(player, player.getLocation()); + } + + @Override + public void updateVisuals(Player player, Vector3 playerLocation) { + globalViewport.updateFor(player, playerLocation); + } + + @Override + public void updateForEntity(VirtualEntity virtualEntity) { + globalViewport.updateEntityViewers(virtualEntity); + } + + @Override + public VirtualEntity spawnModelEntity(Vector3 location, TrainModelItem headModel) { + return spawnVirtualArmorstand(location, new Quaternion(), headModel, VirtualArmorstandConfiguration.createDefault()); + } + + @Override + public VirtualEntity spawnModelEntity(Vector3 location, Quaternion rotation, TrainModelItem headModel, String customName) { + return spawnVirtualArmorstand(location, rotation, headModel, VirtualArmorstandConfiguration.createWithName(customName)); + } + + @Override + public VirtualEntity spawnVirtualEntity(Vector3 location, EntityType entityType) { + return spawnVirtualEntity(location, entityType, 0); + } + + @Override + public VirtualEntity spawnVirtualEntity(Vector3 location, EntityType entityType, double yawRotation) { + int entityId = entityIdFactory.newId(); + VirtualEntity virtualEntity = new VirtualBukkitEntity(packetSender, this, location, entityType, yawRotation, entityId); + + addEntity(virtualEntity); + + updateForEntity(virtualEntity); + return virtualEntity; + } + + @Override + public VirtualArmorstand spawnSeatEntity(Vector3 location, double yawRotation, TrainModelItem model){ + int entityId = entityIdFactory.newId(); + Quaternion rotation = new Quaternion(); + VirtualArmorstand virtualArmorstand = new YawRotatedVirtualArmorstand(packetSender, this, location, rotation, yawRotation, entityId, VirtualArmorstandConfiguration.createDefault()); + if(model != null){ + virtualArmorstand.setModel(model); + } + + addEntity(virtualArmorstand); + + updateForEntity(virtualArmorstand); + return virtualArmorstand; + } + + @Override + public VirtualArmorstand spawnVirtualArmorstand(Vector3 location) { + return spawnVirtualArmorstand(location, new Quaternion(), null, VirtualArmorstandConfiguration.createDefault()); + } + + @Override + public VirtualArmorstand spawnVirtualArmorstand(Vector3 location, double yawRotation) { + return spawnVirtualArmorstand(location, yawRotation); + } + + @Override + public VirtualArmorstand spawnVirtualArmorstand(Vector3 location, Quaternion rotation, TrainModelItem model, VirtualArmorstandConfiguration configuration) { + return spawnVirtualArmorstand(location, rotation, 0, model, configuration); + } + + @Override + public VirtualArmorstand spawnVirtualArmorstand(Vector3 location, Quaternion rotation, double yawRotation, TrainModelItem model, VirtualArmorstandConfiguration configuration) { + int entityId = entityIdFactory.newId(); + VirtualArmorstand virtualArmorstand = new VirtualArmorstand(packetSender, this, location, rotation, yawRotation, entityId, configuration); + if(model != null){ + virtualArmorstand.setModel(model); + } + + addEntity(virtualArmorstand); + + updateForEntity(virtualArmorstand); + return virtualArmorstand; + } + + @Override + public void despawnAll() { + for(VirtualEntity virtualEntity : globalViewport.getEntities()){ + removeEntity(virtualEntity.getEntityId()); + virtualEntity.despawn(); + } + } + + private void flushDeadEntities(){ + globalViewport.flushDeadEntities(); + } +} diff --git a/src/main/java/com/jverbruggen/jrides/state/viewport/SpecifiedViewportManager.java b/src/main/java/com/jverbruggen/jrides/state/viewport/SpecifiedViewportManager.java new file mode 100644 index 00000000..22b449ff --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/state/viewport/SpecifiedViewportManager.java @@ -0,0 +1,125 @@ +package com.jverbruggen.jrides.state.viewport; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.TrainModelItem; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.entity.armorstand.VirtualArmorstand; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.models.render.Viewport; +import com.jverbruggen.jrides.packets.object.VirtualArmorstandConfiguration; +import org.bukkit.entity.EntityType; + +import java.util.ArrayList; +import java.util.List; + +public class SpecifiedViewportManager implements ViewportManager{ + private final List viewports; + private final int renderDistance; + private final int renderChunkSize; + + public SpecifiedViewportManager(int renderDistance, int renderChunkSize) { + this.viewports = new ArrayList<>(); + this.renderDistance = renderDistance; + this.renderChunkSize = renderChunkSize; + } + + @Override + public void updateVisuals(Player player) { + updateVisuals(player, player.getLocation()); + } + + @Override + public void updateVisuals(Player player, Vector3 playerLocation){ + } + + public void updateForEntity(VirtualEntity virtualEntity){ + Vector3 location = virtualEntity.getLocation(); + for(Viewport viewport : viewports){ + boolean isInViewport = viewport.hasEntity(virtualEntity); + boolean shouldBeInViewport = viewport.isInViewport(location); + + if(shouldBeInViewport && !isInViewport){ + viewport.addEntity(virtualEntity); + }else if(!shouldBeInViewport && isInViewport){ + viewport.removeEntity(virtualEntity); + } + } + } + + @Override + public VirtualEntity spawnModelEntity(Vector3 location, TrainModelItem trainModelItem) { + return null; + } + + @Override + public VirtualEntity spawnModelEntity(Vector3 location, Quaternion rotation, TrainModelItem trainModelItem, String customName) { + return null; + } + + @Override + public VirtualEntity spawnSeatEntity(Vector3 location, double yawRotation, TrainModelItem model) { + return null; + } + + @Override + public VirtualEntity spawnVirtualEntity(Vector3 location, EntityType entityType) { + return null; + } + + @Override + public VirtualEntity spawnVirtualEntity(Vector3 location, EntityType entityType, double yawRotation) { + return null; + } + + @Override + public VirtualArmorstand spawnVirtualArmorstand(Vector3 location) { + return null; + } + + @Override + public VirtualArmorstand spawnVirtualArmorstand(Vector3 location, double yawRotation) { + return null; + } + + @Override + public VirtualArmorstand spawnVirtualArmorstand(Vector3 location, Quaternion rotation, TrainModelItem headModel, VirtualArmorstandConfiguration configuration) { + return null; + } + + @Override + public VirtualArmorstand spawnVirtualArmorstand(Vector3 location, Quaternion rotation, double yawRotation, TrainModelItem headModel, VirtualArmorstandConfiguration configuration) { + return null; + } + + @Override + public void despawnAll() { + + } + + @Override + public VirtualEntity getEntity(int entityId) { + return null; + } + + @Override + public int getRenderChunkSize() { + return renderChunkSize; + } + + @Override + public int getRenderDistance() { + return renderDistance; + } + + @Override + public void removeEntities(TrainHandle trainHandle) { + + } + + @Override + public void removeEntities(List trainHandles) { + + } +} diff --git a/src/main/java/com/jverbruggen/jrides/state/viewport/ViewportListener.java b/src/main/java/com/jverbruggen/jrides/state/viewport/ViewportListener.java new file mode 100644 index 00000000..42c2341d --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/state/viewport/ViewportListener.java @@ -0,0 +1,55 @@ +package com.jverbruggen.jrides.state.viewport; + +import com.jverbruggen.jrides.JRidesPlugin; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.state.player.PlayerManager; +import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerTeleportEvent; + +import java.util.Objects; + +public class ViewportListener implements Listener { + private final int chunkSize = 8; + private final ViewportManager viewportManager; + private final PlayerManager playerManager; + + public ViewportListener(ViewportManager viewportManager, PlayerManager playerManager) { + this.viewportManager = viewportManager; + this.playerManager = playerManager; + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onMove(PlayerMoveEvent event){ + if(Vector3.chunkRotated(event.getFrom(), event.getTo(), 8)){ + Player player = playerManager.getPlayer(event.getPlayer()); + viewportManager.updateVisuals(player); + } + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onTeleport(PlayerTeleportEvent event){ + Player player = playerManager.getPlayer(event.getPlayer()); + viewportManager.updateVisuals(player, Objects.requireNonNullElse(Vector3.fromBukkitLocation(event.getTo()), player.getLocation())); + + if(player.isSeated()){ + player.getSeatedOn().setPassenger(null); + } + } + + @EventHandler + public void onJoin(PlayerJoinEvent event){ + Player player = playerManager.getPlayer(event.getPlayer()); + + Bukkit.getScheduler().runTaskLater( + JRidesPlugin.getBukkitPlugin(), + () -> viewportManager.updateVisuals(player), + 5L); + } + +} diff --git a/src/main/java/com/jverbruggen/jrides/state/viewport/ViewportManager.java b/src/main/java/com/jverbruggen/jrides/state/viewport/ViewportManager.java new file mode 100644 index 00000000..28ccf800 --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/state/viewport/ViewportManager.java @@ -0,0 +1,35 @@ +package com.jverbruggen.jrides.state.viewport; + +import com.jverbruggen.jrides.animator.coaster.TrainHandle; +import com.jverbruggen.jrides.models.entity.Player; +import com.jverbruggen.jrides.models.entity.TrainModelItem; +import com.jverbruggen.jrides.models.entity.VirtualEntity; +import com.jverbruggen.jrides.models.entity.armorstand.VirtualArmorstand; +import com.jverbruggen.jrides.models.math.Quaternion; +import com.jverbruggen.jrides.models.math.Vector3; +import com.jverbruggen.jrides.packets.object.VirtualArmorstandConfiguration; +import org.bukkit.entity.EntityType; + +import java.util.List; + +public interface ViewportManager { + void updateVisuals(Player player); + void updateVisuals(Player player, Vector3 playerLocation); + void updateForEntity(VirtualEntity virtualEntity); + VirtualEntity spawnModelEntity(Vector3 location, TrainModelItem headModel); + VirtualEntity spawnModelEntity(Vector3 location, Quaternion rotation, TrainModelItem headModel, String customName); + VirtualEntity spawnSeatEntity(Vector3 location, double yawRotation, TrainModelItem model); + VirtualEntity spawnVirtualEntity(Vector3 location, EntityType entityType); + VirtualEntity spawnVirtualEntity(Vector3 location, EntityType entityType, double yawRotation); + VirtualArmorstand spawnVirtualArmorstand(Vector3 location); + VirtualArmorstand spawnVirtualArmorstand(Vector3 location, double yawRotation); + VirtualArmorstand spawnVirtualArmorstand(Vector3 location, Quaternion rotation, TrainModelItem headModel, VirtualArmorstandConfiguration configuration); + VirtualArmorstand spawnVirtualArmorstand(Vector3 location, Quaternion rotation, double yawRotation, TrainModelItem headModel, VirtualArmorstandConfiguration configuration); + void despawnAll(); + VirtualEntity getEntity(int entityId); + int getRenderChunkSize(); + int getRenderDistance(); + + void removeEntities(TrainHandle trainHandle); + void removeEntities(List trainHandles); +} diff --git a/src/main/java/com/jverbruggen/jrides/state/viewport/ViewportManagerFactory.java b/src/main/java/com/jverbruggen/jrides/state/viewport/ViewportManagerFactory.java new file mode 100644 index 00000000..5a10e62b --- /dev/null +++ b/src/main/java/com/jverbruggen/jrides/state/viewport/ViewportManagerFactory.java @@ -0,0 +1,27 @@ +package com.jverbruggen.jrides.state.viewport; + +import com.jverbruggen.jrides.models.entity.EntityIdFactory; +import com.jverbruggen.jrides.models.render.GlobalViewport; +import com.jverbruggen.jrides.packets.PacketSender; +import com.jverbruggen.jrides.serviceprovider.ServiceProvider; + +public class ViewportManagerFactory { + private final PacketSender packetSender; + private final EntityIdFactory entityIdFactory; + + public ViewportManagerFactory() { + this.packetSender = ServiceProvider.getSingleton(PacketSender.class); + this.entityIdFactory = ServiceProvider.getSingleton(EntityIdFactory.class); + } + + public ViewportManager createViewportManager(boolean globalMode){ + int renderDistance = 100; + int renderChunkSize = 8; + + if(globalMode){ + return new GlobalViewportManager(new GlobalViewport(renderDistance), packetSender, entityIdFactory, renderDistance, renderChunkSize); + }else{ + return new SpecifiedViewportManager(renderDistance, renderChunkSize); + } + } +} diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml new file mode 100644 index 00000000..a3ba6830 --- /dev/null +++ b/src/main/resources/plugin.yml @@ -0,0 +1,11 @@ +main: com.jverbruggen.jrides.Main +name: jrides +version: ${minecraft.version.short} +authors: [MeneerPinguin] +api-version: ${minecraft.version.apiversion} +load: POSTWORLD +depend: [ProtocolLib] +permissions: + +commands: + jrides: \ No newline at end of file diff --git a/src/test/java/com/jverbruggen/jrides/animator/flatride/rotor/RotorPlayerControlTest.java b/src/test/java/com/jverbruggen/jrides/animator/flatride/rotor/RotorPlayerControlTest.java new file mode 100644 index 00000000..75787dc2 --- /dev/null +++ b/src/test/java/com/jverbruggen/jrides/animator/flatride/rotor/RotorPlayerControlTest.java @@ -0,0 +1,51 @@ +//package com.jverbruggen.jrides.animator.flatride.rotor; +// +//import com.jverbruggen.jrides.animator.flatride.rotor.axis.RotorAxis; +//import com.jverbruggen.jrides.animator.flatride.rotor.axis.RotorAxisFactory; +//import org.junit.Test; +//import org.junit.Before; +// +//import com.jverbruggen.jrides.animator.flatride.FlatRideComponentSpeed; +//import com.jverbruggen.jrides.api.JRidesPlayer; +//import com.jverbruggen.jrides.api.JRidesPlayerMock; +// +//import static org.junit.jupiter.api.Assertions.*; +// +//import java.util.Collections; +// +//public class RotorPlayerControlTest { +// private static double EPSILON = 0.0001; +// +// private FlatRideComponentSpeed componentSpeed; +// private Rotor rotor; +// private RotorPlayerControl rotorPlayerControl; +// +// @Before +// public void before(){ +// componentSpeed = new FlatRideComponentSpeed(0d); +// rotorPlayerControl = new RotorTargetPositionPlayerControl(0, 90, .5f); +// RotorAxis rotorAxis = RotorAxisFactory.createAxisX(); +// rotor = new Rotor("", "", false, Collections.emptyList(), componentSpeed, rotorAxis); +// rotorPlayerControl.setRotor(rotor); +// +// JRidesPlayer player = new JRidesPlayerMock(); +// rotorPlayerControl.addControlling(player); +// } +// +// @Test +// public void rotorStaysAtZeroWithNoSpeed(){ +// assertTrue(equals(rotor.getRotorRotation(), 0d)); +// rotorPlayerControl.apply(); +// assertTrue(equals(rotor.getRotorRotation(), 0d)); +// +// for(int i = 0; i < 500; i++){ +// rotorPlayerControl.apply(); +// } +// +// assertTrue(equals(rotor.getRotorRotation(), 0d)); +// } +// +// private boolean equals(double a, double b){ +// return Math.abs(a - b) < EPSILON; +// } +//} diff --git a/src/test/java/com/jverbruggen/jrides/animator/flatride/rotor/RotorTest.java b/src/test/java/com/jverbruggen/jrides/animator/flatride/rotor/RotorTest.java new file mode 100644 index 00000000..8c1f04dc --- /dev/null +++ b/src/test/java/com/jverbruggen/jrides/animator/flatride/rotor/RotorTest.java @@ -0,0 +1,184 @@ +//package com.jverbruggen.jrides.animator.flatride.rotor; +// +//import com.jverbruggen.jrides.animator.flatride.FlatRideComponentSpeed; +//import com.jverbruggen.jrides.animator.flatride.attachment.FixedAttachment; +//import com.jverbruggen.jrides.animator.flatride.rotor.axis.RotorAxis; +//import com.jverbruggen.jrides.animator.flatride.rotor.axis.RotorAxisFactory; +//import com.jverbruggen.jrides.models.math.Quaternion; +//import com.jverbruggen.jrides.models.math.Vector3; +//import org.junit.Before; +//import org.junit.Test; +// +//import java.util.Collections; +// +//import static org.junit.jupiter.api.Assertions.*; +// +//public class RotorTest { +// +// private Rotor rotor; +// +// @Before +// public void setUp(){ +// RotorAxis rotorAxis = RotorAxisFactory.createAxisX(); +// rotor = new Rotor("", "", false, Collections.emptyList(), new FlatRideComponentSpeed(0d, -1d, 1d), rotorAxis); +// rotor.setAttachedTo(new FixedAttachment(rotor, new Vector3(0,0,0), new Quaternion())); +// } +// +// @Test +// public void hasPassed() { +// assertTrue(rotor.hasPassed(0, 0, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(0, 1, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(0, 10, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(0, 359, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// } +// +// @Test +// public void hasPassedWithRotation(){ +// rotor.setInstructionPosition(200); +// +// assertTrue(rotor.hasPassed(0, 0, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(0, 50, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(0, 199, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(0, 200, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(0, 201, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(0, 359, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// } +// +// @Test +// public void hasPassedWithRotationFromNegativeZeroPosition(){ +// rotor.setInstructionPosition(-0d); +// +// assertTrue(rotor.hasPassed(0, 0, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(0, 30, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(0, 199, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(0, 200, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(0, 201, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(0, 359, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// } +// +// @Test +// public void hasPassedWithRotationFromX(){ +// rotor.setInstructionPosition(200); +// double from = 50; +// +// assertTrue(rotor.hasPassed(from, 50, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(from, 199, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(from, 200, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 201, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 359, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 0, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 15, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 49, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// } +// +// @Test +// public void hasPassedWithRotationFromHighX(){ +// rotor.setInstructionPosition(200); +// double from = 190; +// +// assertFalse(rotor.hasPassed(from, 50, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 189, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(from, 190, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(from, 191, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(from, 199, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(from, 200, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 201, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 359, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 0, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 15, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 49, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// } +// +// @Test +// public void hasPassedWithRotationLowXLowPos(){ +// rotor.setInstructionPosition(50); +// double from = 30; +// +// assertFalse(rotor.hasPassed(from, 20, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 29, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(from, 30, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(from, 31, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(from, 49, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(from, 50, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 51, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 359, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 0, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// } +// +// @Test +// public void hasPassedWithRotationBackwards(){ +// rotor.setInstructionPosition(200); +// rotor.getFlatRideComponentSpeed().accelerate(-2); // Make the speed negative +// +// assertFalse(rotor.hasPassed(0, 0, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(0, 50, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(0, 199, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(0, 200, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(0, 201, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(0, 359, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// } +// +// @Test +// public void hasPassedWithRotationBackwardsLowPos(){ +// rotor.setInstructionPosition(30); +// rotor.getFlatRideComponentSpeed().accelerate(-2); // Make the speed negative +// +// assertFalse(rotor.hasPassed(0, 0, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(0, 20, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(0, 29, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(0, 30, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(0, 31, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(0, 180, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(0, 300, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(0, 359, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// } +// +// @Test +// public void hasPassedWithRotationFromXBackwards(){ +// rotor.setInstructionPosition(200); +// rotor.getFlatRideComponentSpeed().accelerate(-2); // Make the speed negative +// double from = 290; +// System.out.println(rotor.getRotorRotation() + " curpos"); +// +// assertFalse(rotor.hasPassed(from, 50, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 199, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(from, 200, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(from, 201, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(from, 288, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(from, 289, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// +// assertFalse(rotor.hasPassed(from, 290, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d), "Should actually be true, but its weird"); +// +// assertFalse(rotor.hasPassed(from, 291, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 292, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 359, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 0, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 15, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 49, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// } +// +// @Test +// public void hasPassedWithRotationFromXBackwardsLowXLowPos(){ +// rotor.setInstructionPosition(10); +// rotor.getFlatRideComponentSpeed().accelerate(-2); // Make the speed negative +// double from = 50; +// System.out.println(rotor.getRotorRotation() + " curpos"); +// +// assertFalse(rotor.hasPassed(from, 5, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 9, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(from, 10, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(from, 11, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(from, 35, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertTrue(rotor.hasPassed(from, 49, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// +// assertFalse(rotor.hasPassed(from, 50, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d), "Should actually be true, but its weird"); +// +// assertFalse(rotor.hasPassed(from, 51, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 52, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 100, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 292, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 359, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 360, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// assertFalse(rotor.hasPassed(from, 0, rotor.getFlatRideComponentSpeed().getSpeed() >= 0, 0d)); +// } +//} \ No newline at end of file diff --git a/src/test/java/com/jverbruggen/jrides/api/JRidesPlayerMock.java b/src/test/java/com/jverbruggen/jrides/api/JRidesPlayerMock.java new file mode 100644 index 00000000..420b74bb --- /dev/null +++ b/src/test/java/com/jverbruggen/jrides/api/JRidesPlayerMock.java @@ -0,0 +1,40 @@ +package com.jverbruggen.jrides.api; + +import java.util.UUID; + +import org.bukkit.entity.Player; + +public class JRidesPlayerMock implements JRidesPlayer { + private boolean seated = false; + + @Override + public Player getBukkitPlayer() { + throw new UnsupportedOperationException("Unimplemented method 'getBukkitPlayer'"); + } + + @Override + public String getName() { + return "MockPlayer"; + } + + @Override + public String getIdentifier() { + return "mockplayer"; + } + + @Override + public UUID getUniqueId(){ + return UUID.randomUUID(); + } + + @Override + public boolean isSeated() { + return this.seated; + } + + @Override + public void sendTitle(String title, String subtitle, int stay) { + return; + } + +} diff --git a/src/test/java/com/jverbruggen/jrides/models/math/MathUtilTest.java b/src/test/java/com/jverbruggen/jrides/models/math/MathUtilTest.java new file mode 100644 index 00000000..f55b7ace --- /dev/null +++ b/src/test/java/com/jverbruggen/jrides/models/math/MathUtilTest.java @@ -0,0 +1,16 @@ +package com.jverbruggen.jrides.models.math; + +import org.junit.Test; + +import static org.junit.jupiter.api.Assertions.*; + +public class MathUtilTest { + + @Test + public void floorMod() { + assertEquals(0f, MathUtil.floorMod(0f, 360f)); + assertEquals(0f, MathUtil.floorMod(360f, 360f)); + assertEquals(180f, MathUtil.floorMod(180f, 360f)); + assertEquals(260f, MathUtil.floorMod(-100f, 360f)); + } +} \ No newline at end of file diff --git a/src/test/java/com/jverbruggen/jrides/models/math/SpeedUtilTest.java b/src/test/java/com/jverbruggen/jrides/models/math/SpeedUtilTest.java new file mode 100644 index 00000000..1d304c7a --- /dev/null +++ b/src/test/java/com/jverbruggen/jrides/models/math/SpeedUtilTest.java @@ -0,0 +1,110 @@ +package com.jverbruggen.jrides.models.math; + +import org.junit.Test; +import org.junit.jupiter.api.DisplayName; + +import static org.junit.jupiter.api.Assertions.*; + +public class SpeedUtilTest { + @Test + @DisplayName("Position start braking") + public void positionStartBrakingTest(){ + assertEquals(95d, SpeedUtil.positionStartBraking(1d, -.1d, 100d, 0d)); + assertEquals(480d, SpeedUtil.positionStartBraking(2d, -.1d, 500d, 0d)); + } + + @Test + public void testRangeNormal(){ + assertFalse(SpeedUtil.inRange(90, 89, 120)); + assertTrue(SpeedUtil.inRange(90, 90, 120)); + assertTrue(SpeedUtil.inRange(90, 100, 120)); + assertTrue(SpeedUtil.inRange(90, 119, 120)); + assertTrue(SpeedUtil.inRange(90, 120, 120)); + assertFalse(SpeedUtil.inRange(90, 121, 120)); + } + + @Test + public void testRangeRotated(){ + assertFalse(SpeedUtil.inRange(120, 119, 90)); + assertTrue(SpeedUtil.inRange(120, 120, 90)); + assertTrue(SpeedUtil.inRange(120, 121, 90)); + assertTrue(SpeedUtil.inRange(120, 360, 90)); + assertTrue(SpeedUtil.inRange(120, 0, 90)); + assertTrue(SpeedUtil.inRange(120, 89, 90)); + assertTrue(SpeedUtil.inRange(120, 90, 90)); + assertFalse(SpeedUtil.inRange(120, 91, 90)); + assertFalse(SpeedUtil.inRange(120, 100, 90)); + } + + @Test + public void hasPassedForwardsNormal(){ + assertTrue(SpeedUtil.hasPassed(10, 9, 30, true)); + assertFalse(SpeedUtil.hasPassed(10, 10, 30, true)); + assertFalse(SpeedUtil.hasPassed(10, 11, 30, true)); + assertFalse(SpeedUtil.hasPassed(10, 20, 30, true)); + assertFalse(SpeedUtil.hasPassed(10, 29, 30, true)); + assertTrue(SpeedUtil.hasPassed(10, 30, 30, true)); + assertTrue(SpeedUtil.hasPassed(10, 31, 30, true)); + } + + @Test + public void hasPassedForwardsRotate(){ + assertTrue(SpeedUtil.hasPassed(270, 250, 45, true)); + assertFalse(SpeedUtil.hasPassed(270, 270, 45, true)); + assertFalse(SpeedUtil.hasPassed(270, 271, 45, true)); + assertFalse(SpeedUtil.hasPassed(270, 360, 45, true)); + assertFalse(SpeedUtil.hasPassed(270, 0, 45, true)); + assertFalse(SpeedUtil.hasPassed(270, 44, 45, true)); + assertTrue(SpeedUtil.hasPassed(270, 45, 45, true)); + assertTrue(SpeedUtil.hasPassed(270, 46, 45, true)); + assertTrue(SpeedUtil.hasPassed(270, 50, 45, true)); + } + + @Test + public void hasPassedBackwards(){ + assertTrue(SpeedUtil.hasPassed(30, 270, 10, false)); + assertTrue(SpeedUtil.hasPassed(30, 180, 10, false)); + assertTrue(SpeedUtil.hasPassed(30, 31, 10, false)); + assertFalse(SpeedUtil.hasPassed(30, 30, 10, false)); + assertFalse(SpeedUtil.hasPassed(30, 29, 10, false)); + assertFalse(SpeedUtil.hasPassed(30, 20, 10, false)); + assertFalse(SpeedUtil.hasPassed(30, 11, 10, false)); + assertTrue(SpeedUtil.hasPassed(30, 10, 10, false)); + assertTrue(SpeedUtil.hasPassed(30, 9, 10, false)); + } + + @Test + public void hasPassedBackwardsRotate(){ + assertTrue(SpeedUtil.hasPassed(100, 120, 150, false)); + assertTrue(SpeedUtil.hasPassed(100, 101, 150, false)); + assertFalse(SpeedUtil.hasPassed(100, 100, 150, false)); + assertFalse(SpeedUtil.hasPassed(100, 99, 150, false)); + assertFalse(SpeedUtil.hasPassed(100, 50, 150, false)); + assertFalse(SpeedUtil.hasPassed(100, 0, 150, false)); + assertFalse(SpeedUtil.hasPassed(100, 360, 150, false)); + assertFalse(SpeedUtil.hasPassed(100, 270, 150, false)); + assertFalse(SpeedUtil.hasPassed(100, 151, 150, false)); + assertTrue(SpeedUtil.hasPassed(100, 150, 150, false)); + assertTrue(SpeedUtil.hasPassed(100, 149, 150, false)); + } + + @Test + public void aboveInRange(){ + assertTrue(SpeedUtil.aboveInRange(0, 30, 50, 80, true)); + assertTrue(SpeedUtil.aboveInRange(0, 49, 50, 80, true)); + assertTrue(SpeedUtil.aboveInRange(0, 50, 50, 80, true)); + assertFalse(SpeedUtil.aboveInRange(0, 51, 50, 80, true)); + assertFalse(SpeedUtil.aboveInRange(0, 80, 50, 80, true)); + } + + @Test + public void aboveInRangeRotate(){ + assertTrue(SpeedUtil.aboveInRange(320, 322, 20, 40, true)); + assertTrue(SpeedUtil.aboveInRange(320, 360, 20, 40, true)); + assertTrue(SpeedUtil.aboveInRange(320, 0, 20, 40, true)); + assertTrue(SpeedUtil.aboveInRange(320, 19, 20, 40, true)); + assertTrue(SpeedUtil.aboveInRange(320, 20, 20, 40, true)); + assertFalse(SpeedUtil.aboveInRange(320, 21, 20, 40, true)); + assertFalse(SpeedUtil.aboveInRange(320, 22, 20, 40, true)); + } +} \ No newline at end of file diff --git a/tools/create_special_source.sh b/tools/create_special_source.sh new file mode 100644 index 00000000..81999952 --- /dev/null +++ b/tools/create_special_source.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +MINECRAFT_VERSION=$1 +PLUGIN=$2 + +if [[ "$PLUGIN" == "" || "$MINECRAFT_VERSION" == "" ]]; then + echo "Usage create_special_source.sh " + echo -n "Press enter to continue.." + read exitread + exit 1 +fi + +# https://www.spigotmc.org/threads/spigot-bungeecord-1-17-1-17-1.510208/#post-4184317 +java -cp $HOME/.m2/repository/net/md-5/SpecialSource/1.11.0/SpecialSource-1.11.0-shaded.jar:$HOME/.m2/repository/org/spigotmc/spigot/$MINECRAFT_VERSION-R0.1-SNAPSHOT/spigot-$MINECRAFT_VERSION-R0.1-SNAPSHOT-remapped-mojang.jar net.md_5.specialsource.SpecialSource --live -i $PLUGIN.jar -o $PLUGIN-obf.jar -m $HOME/.m2/repository/org/spigotmc/minecraft-server/$MINECRAFT_VERSION-R0.1-SNAPSHOT/minecraft-server-$MINECRAFT_VERSION-R0.1-SNAPSHOT-maps-mojang.txt --reverse +java -cp $HOME/.m2/repository/net/md-5/SpecialSource/1.11.0/SpecialSource-1.11.0-shaded.jar:$HOME/.m2/repository/org/spigotmc/spigot/$MINECRAFT_VERSION-R0.1-SNAPSHOT/spigot-$MINECRAFT_VERSION-R0.1-SNAPSHOT-remapped-obf.jar net.md_5.specialsource.SpecialSource --live -i $PLUGIN-obf.jar -o $PLUGIN.jar -m $HOME/.m2/repository/org/spigotmc/minecraft-server/$MINECRAFT_VERSION-R0.1-SNAPSHOT/minecraft-server-$MINECRAFT_VERSION-R0.1-SNAPSHOT-maps-spigot.csrg + +read exitread +exit 0 \ No newline at end of file diff --git a/tools/generate_language_md.py b/tools/generate_language_md.py new file mode 100644 index 00000000..2dd97de3 --- /dev/null +++ b/tools/generate_language_md.py @@ -0,0 +1,62 @@ +import re + +java_file_path = "src/main/java/com/jverbruggen/jrides/language/LanguageFile.java" +expression = r"\);*\n?\s+setLanguageDefault\(LanguageFileField.|\);\s*\/\/\sEnd\sof\slanguage\sdefinitions" +language_file_path = "docs/language.md" + +java_tags_file_path = "src/main/java/com/jverbruggen/jrides/language/LanguageFileTag.java" +tags_expression = r"{{1}\n\s+public\sstatic\sfinal\sString\s|public\sstatic\sfinal\sString\s|;\n\s+|;\n" + +tag_replacement_base_expression = r"\"\s\+\sLanguageFileTag.{java_name}\s\+\s\"" + +content = """ +# Language + +Also see: [docs/config.md](./config.md) + +Example language file (plugins/jrides/language.yml): +```yaml +language: + NOTIFICATION_RIDE_COUNTER_UPDATE: "&4-------\\n \\n&6You have been %RIDE_COUNT% times in %RIDE_DISPLAY_NAME%!\\n \\n&4-------" + NOTIFICATION_CANNOT_ENTER_RIDE: "&7This ride is temporarily unavailable." +``` + +Key | Default value +--- | --- +""" + +tags = [] + +with open(java_tags_file_path) as f: + file_content = f.read() + split = re.split(tags_expression, file_content)[2:-1] + + for item in split: + if item == "": continue + item_split = item.split(" = ") + java_name = item_split[0] + replace_name = item_split[1].replace("\"", "") + res = (java_name, replace_name) + tags += [res] + +grouped = [] +with open(java_file_path) as f: + file_content = f.read() + split = re.split(expression, file_content)[1:-1] + + for item in split: + t = tuple(item.split(sep=', ', maxsplit=1)) + + value = t[1] + + for (java_name, replace_name) in tags: + tag_replacement_expression = tag_replacement_base_expression.format(java_name=java_name) + value = re.sub(tag_replacement_expression, replace_name, value) + + content += f"{t[0]} | {value}\n" + +with open(language_file_path, 'w') as f: + f.write(content) + +print("Done!") + diff --git a/tools/generate_permissions_md.py b/tools/generate_permissions_md.py new file mode 100644 index 00000000..d0a23326 --- /dev/null +++ b/tools/generate_permissions_md.py @@ -0,0 +1,30 @@ +import re + +java_file_path = "src/main/java/com/jverbruggen/jrides/common/permissions/Permissions.java" +permission_groups_re = r'\s+\/\/\/\s|}' +permission_split_re = r'\s=\s\"|\";\s\/\/\s' +language_file_path = "docs/permissions.md" + +table_template = "Permission | Description\n--- | ---" +content = "# Permissions\n" + +grouped = [] +with open(java_file_path) as f: + file_content = f.read() + permission_groups = re.split(permission_groups_re, file_content)[1:-1] + + for p_group in permission_groups: + values = re.split(r'\n\s+', str(p_group)) + title = values[0] + permissions = values[1::] + + permissions_tuples = [tuple(re.split(permission_split_re, permission)[1:]) for permission in permissions] + table_contents = '\n'.join([f"{permission} | {description}" for permission, description in permissions_tuples]) + + content += f"\n## {title}\n\n{table_template}\n{table_contents}\n" + +with open(language_file_path, 'w') as f: + f.write(content) + +print("Done!") + diff --git a/tools/jrides_blender_export_anim_plugin.py b/tools/jrides_blender_export_anim_plugin.py new file mode 100644 index 00000000..6b7f7cbe --- /dev/null +++ b/tools/jrides_blender_export_anim_plugin.py @@ -0,0 +1,81 @@ +# Script from ottle, with some changes specific to jrides. + +bl_info = { + "name": "JRides Export Animation", + "author": "ottle,jverbruggen", + "version": (0, 1), + "blender": (2, 80, 0), + "location": "File > Export > JRidesAnimation (.csv)", + "description": "JRides Export Animation (.csv)", + "warning": "", + "wiki_url": "", + "support": 'COMMUNITY', + "category": "Import-Export", +} + +import os +import bpy + +def write_anim(context, filepath, frame_start, frame_end): + fw = open(filepath, 'w').write + fw("object,frame,posx,posy,posz,scalex,scaley,scalez,rw,rx,ry,rz\n") + frame_range = range(frame_start, frame_end + 1) + for obj in bpy.context.selected_objects: + for f in frame_range: + bpy.context.scene.frame_set(f) + matrix = obj.matrix_world.copy() + posx, posy, posz = matrix.to_translation()[:] + scalex, scaley, scalez = matrix.to_scale()[:] + rw, rx, ry, rz = matrix.to_quaternion()[:] + fw("%s, %d, %r, %r, %r, %r, %r, %r, %r, %r, %r, %r\n" + % (obj.name, f, posx,posy,posz, scalex,scaley,scalez, rw, rx, ry, rz)) + +from bpy.props import StringProperty, IntProperty, BoolProperty +from bpy_extras.io_utils import ExportHelper + + +class AnimationExporter(bpy.types.Operator, ExportHelper): + """Save selected object animations as a csv file.""" + bl_idname = "export_animation.objects" + bl_label = "JRides Animation" + + filename_ext = ".csv" + filter_glob: StringProperty(default="*.csv", options={'HIDDEN'}) + + frame_start: IntProperty(name="Start Frame", + description="Start frame for export", + default=1, min=1, max=300000) + frame_end: IntProperty(name="End Frame", + description="End frame for export", + default=250, min=1, max=300000) + + def execute(self, context): + write_anim(context, self.filepath, self.frame_start, self.frame_end) + return {'FINISHED'} + + def invoke(self, context, event): + self.frame_start = context.scene.frame_start + self.frame_end = context.scene.frame_end + + wm = context.window_manager + wm.fileselect_add(self) + return {'RUNNING_MODAL'} + + +def menu_export(self, context): + default_path = os.path.splitext(bpy.data.filepath)[0] + ".csv" + self.layout.operator(AnimationExporter.bl_idname, text="JRides Animation (.csv)") + + +def register(): + bpy.utils.register_class(AnimationExporter) + bpy.types.TOPBAR_MT_file_export.append(menu_export) + + +def unregister(): + bpy.utils.unregister_class(AnimationExporter) + bpy.types.TOPBAR_MT_file_export.remove(menu_export) + + +if __name__ == "__main__": + register() diff --git a/tools/nolimits_csv_validator.py b/tools/nolimits_csv_validator.py new file mode 100644 index 00000000..cedecf85 --- /dev/null +++ b/tools/nolimits_csv_validator.py @@ -0,0 +1,56 @@ +import csv +import argparse +import os +import math + +parser = argparse.ArgumentParser(description='Nolimits CSV validator for jrides') +parser.add_argument('csv_file') +args = parser.parse_args() + +csv_file = args.csv_file +if not os.path.exists(csv_file): + print(f"Path '{csv_file}' does not exist") + exit(1) + +prev_x = None +prev_y = None +prev_z = None + +final_d = 0 + +with open(csv_file, 'r') as f: + reader = csv.reader(f, delimiter='\t') + + for i, row in enumerate(reader): + if i == 0: continue + + x = float(row[1]) + y = float(row[2]) + z = float(row[3]) + + if prev_x is not None: + dx = abs(x - prev_x) + dy = abs(y - prev_y) + dz = abs(z - prev_z) + + # Distance 3D + d = math.sqrt(dx*dx + dy*dy + dz*dz) + + d_display = "{:.3f}".format(d) + + print("P-Distance: {}".format(d_display)) + + if i > 5: + final_d = d + break + + prev_x = x + prev_y = y + prev_z = z + +print("P-Distance should be around 0.050") + +if float(d_display) == 0.050: + print("Result: OK") +else: + print("Result: Not OK")